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
- Variables
- func Escape(s string) string
- func MaskToken(token string) string
- func ModuleText(name, text string) string
- func NewCode() (string, error)
- func NotHolder(err error) bool
- func Refused(err error) bool
- func ServeHub(h Hub, s Sender, w http.ResponseWriter, r *http.Request)
- func StartLink(bot, code string) string
- func TooLarge(err error) bool
- func Unauthorized(err error) bool
- type APIError
- type Bridge
- func (b *Bridge) Act(ctx context.Context, p HubPress) HubResult
- func (b *Bridge) Active() bool
- func (b *Bridge) Answerable() bool
- func (b *Bridge) CancelPairing()
- func (b *Bridge) Connect(ctx context.Context, token string) (User, error)
- func (b *Bridge) Converse(id string)
- func (b *Bridge) Conversing(id string) bool
- func (b *Bridge) Deliver(m Out, ref Ref, done func(error))
- func (b *Bridge) Disconnect() error
- func (b *Bridge) EditModule(ctx context.Context, e ModuleEdit) error
- func (b *Bridge) FromHub(hm HubMessage)
- func (b *Bridge) Handover(ctx context.Context, s Sender) (Handover, error)
- func (b *Bridge) HubInfo() HubInfo
- func (b *Bridge) HubPost(ctx context.Context, s Sender, m HubMessage) (int64, error)
- func (b *Bridge) HubPresses(ctx context.Context, s Sender, wait time.Duration) []HubPress
- func (b *Bridge) HubResult(ctx context.Context, s Sender, r HubResult) error
- func (b *Bridge) Muted(id string) bool
- func (b *Bridge) QueuedSent(queued int64)
- func (b *Bridge) ReplyOnce(id string)
- func (b *Bridge) Replying(id string) bool
- func (b *Bridge) Routing() bool
- func (b *Bridge) Run(ctx context.Context)
- func (b *Bridge) SendModule(ctx context.Context, m ModuleMessage) (int64, error)
- func (b *Bridge) SendNow(ctx context.Context, m Out) error
- func (b *Bridge) SendPhoto(ctx context.Context, png []byte, caption string) error
- func (b *Bridge) StartPairing() (Pairing, error)
- func (b *Bridge) Status() Status
- func (b *Bridge) TakeOver(ctx context.Context, h Handover, self, from string) error
- func (b *Bridge) TakeReplyOnce(id string) bool
- func (b *Bridge) Wake()
- type CallbackQuery
- type Candidate
- type Carried
- type CarriedView
- type Chat
- type Client
- func (c *Client) AnswerCallbackQuery(ctx context.Context, id, text string) error
- func (c *Client) Call(ctx context.Context, method string, params, out any) error
- func (c *Client) Download(ctx context.Context, fileID string, limit int64) ([]byte, error)
- func (c *Client) EditMarkup(ctx context.Context, chatID string, messageID int64, markup *Markup) error
- func (c *Client) EditText(ctx context.Context, chatID string, messageID int64, text, parseMode string, ...) error
- func (c *Client) GetMe(ctx context.Context) (User, error)
- func (c *Client) GetUpdates(ctx context.Context, offset int64, wait time.Duration) ([]Update, error)
- func (c *Client) Pin(ctx context.Context, chatID string, messageID int64) error
- func (c *Client) React(ctx context.Context, chatID string, messageID int64, emoji string) error
- func (c *Client) SendMessage(ctx context.Context, s Send) (Message, error)
- func (c *Client) SendPhoto(ctx context.Context, chatID string, png []byte, caption string) (Message, error)
- func (c *Client) SetCommands(ctx context.Context, cmds []Command) error
- func (c *Client) Unpin(ctx context.Context, chatID string, messageID int64) error
- type Command
- type FileRef
- type ForceReply
- type ForwardOrigin
- type Handover
- type Host
- type Hub
- type HubButton
- type HubClient
- func (c HubClient) Handover(ctx context.Context) (Handover, error)
- func (c HubClient) Info(ctx context.Context) (HubInfo, error)
- func (c HubClient) Post(ctx context.Context, m HubMessage) (int64, error)
- func (c HubClient) Presses(ctx context.Context, wait time.Duration) ([]HubPress, error)
- func (c HubClient) Result(ctx context.Context, r HubResult) error
- type HubError
- type HubInfo
- type HubMessage
- type HubPress
- type HubResult
- type InlineButton
- type Live
- type Markup
- type Message
- type ModuleButton
- type ModuleEdit
- type ModuleMessage
- type Moved
- type Out
- type Outbox
- type Pairing
- type PhotoSize
- type PinError
- type Poller
- type Project
- type Ref
- type Send
- type Sender
- type State
- type Status
- type Store
- func (s *Store) Get() State
- func (s *Store) IsMuted(sessionID string) bool
- func (s *Store) Lookup(messageID int64) (Ref, bool)
- func (s *Store) LookupRemote(machine, remote string) (Ref, bool)
- func (s *Store) NextAnswer(messageID int64) int
- func (s *Store) Remember(r Ref)
- func (s *Store) Reset() error
- func (s *Store) Update(f func(*State)) error
- func (s *Store) UpdateRef(messageID int64, f func(*Ref)) bool
- type Update
- type User
- type ViaStatus
Constants ¶
const ( ActApprove = "approve" ActDeny = "deny" ActMute = "mute" ActReply = "reply" )
The actions a button on a message from another computer may carry, and a reply to it. Anything else is dropped from the message.
const ( HubPath = "/v1/telegram/hub" HubMessagesPath = "/v1/telegram/hub/messages" HubPressesPath = "/v1/telegram/hub/presses" HubResultsPath = "/v1/telegram/hub/results" HubHandoverPath = "/v1/telegram/hub/handover" )
The hub's wire: the holder's routes as another computer calls them over their link (ADR-067), served by ServeHub and called by HubClient. The routes are registered by the API, which decides who may call them (a computer the owner allowed, never a phone) and names the Sender from its own device record.
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 )
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.
const CodeDigits = 6
CodeDigits is the length of a pairing code.
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.
const ( // DefaultBurstWait is how long the chat must be quiet before a burst of // forwards is asked about. DefaultBurstWait = 2 * time.Second )
const HubPressWait = 25 * time.Second
HubPressWait is the longest a presses request is held open.
const MaxCaption = 1024
MaxCaption is the longest photo caption Telegram takes, in characters.
const MaxDownload = 20 << 20
MaxDownload is the largest file the Bot API lets a bot fetch.
const ( // PairFor is how long a pairing code works. PairFor = 10 * time.Minute )
const PremiumURL = "https://caprock.dev/premium/"
PremiumURL is where the Premium line points.
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 ¶
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.
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).
var ErrExpired = errors.New("telegram: dropped, too late to be useful")
ErrExpired is an Out dropped because it waited past its Expires.
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.
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.
var ErrNoToken = errors.New("telegram: no bot token")
ErrNoToken is a call made with no token at all.
var ErrNotHolder error = sentence("This computer has no Telegram bot connected, so it cannot carry another computer's messages.")
ErrNotHolder is a hub request to a machine with no bot and chat of its own.
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.
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.
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.
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 MaskToken ¶
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
ModuleText is the message as Telegram gets it, in HTML: the module's name on the first line, then its text, escaped.
func Refused ¶ added in v0.200.0
Refused reports an answer that will not change on a retry: the message itself was refused (400), or the route is not there (404, 403 — an older Caprock, or a computer not allowed to). A 502 (Telegram's) or a transport error is worth trying again.
func ServeHub ¶ added in v0.200.0
ServeHub answers one hub request from computer s:
GET /v1/telegram/hub → HubInfo
POST /v1/telegram/hub/messages HubMessage → {message_id}; 409 not a holder, 400 a message it will not post, 502 Telegram's words
GET /v1/telegram/hub/presses?wait=<s> → {presses: [HubPress]} (held up to 25 s while none waits)
POST /v1/telegram/hub/results HubResult → {ok}; 404 for a message it never posted
POST /v1/telegram/hub/handover → Handover; 409 not a holder
func StartLink ¶
StartLink is the t.me link that opens the bot and sends "/start <code>" in one tap.
func TooLarge ¶ added in v0.137.0
TooLarge reports whether err is Download refusing a file for its size.
func Unauthorized ¶
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.
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
// One bot for several computers (hub.go, via.go). Via is the holder this
// machine sends through ("" for none); Route hands it one message, done
// hearing whether the holder took it; ViaStatus is that link as Settings
// shows it. All nil on a machine that never sends through another.
// OnMoved hears that this machine handed its bot to another computer.
Via func() string
Route func(m HubMessage, done func(error))
ViaStatus func() *ViaStatus
OnMoved func(to Sender)
// 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 (*Bridge) Act ¶ added in v0.200.0
Act does what a press or a reply under one of this machine's messages asked, on this machine and by its own rules: the session it was about, a licence and the two-way switch here for anything but Mute, and rule 7 in Host. The result is what the holder shows in the chat.
func (*Bridge) Active ¶
Active reports whether two-way chat works right now: licensed, switched on, and a chat paired.
func (*Bridge) Answerable ¶ added in v0.200.0
Answerable reports a message about a session handed to the holder within viaPollFor: the sender asks for presses only then.
func (*Bridge) CancelPairing ¶
func (b *Bridge) CancelPairing()
CancelPairing ends a pairing in progress.
func (*Bridge) Connect ¶
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 ¶
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 ¶
Conversing reports whether the owner typed into a session from Telegram within the last hour.
func (*Bridge) Deliver ¶
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. On a machine that sends through a holder the message goes there instead.
func (*Bridge) Disconnect ¶
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) FromHub ¶ added in v0.200.0
func (b *Bridge) FromHub(hm HubMessage)
FromHub is a queued message sent through this machine's own bot after all (it became the holder while the message waited): the alert's buttons again, and the session it was about remembered under its Telegram id.
func (*Bridge) Handover ¶ added in v0.200.0
Handover gives this machine's bot to the computer that asks: the token, the paired chat and where reading stopped. This machine then forgets the bot exactly as Disconnect does, stops reading (Telegram lets one reader at a time), and remembers where the bot went. OnMoved, when set, hears who took it.
func (*Bridge) HubInfo ¶ added in v0.200.0
HubInfo says whether this machine holds a bot others can send through.
func (*Bridge) HubPost ¶ added in v0.200.0
HubPost posts another computer's message to the paired chat, under a first line naming that computer, and returns its Telegram message id. A message already posted under the same id is not posted again: a sender that lost the answer asks again.
func (*Bridge) HubPresses ¶ added in v0.200.0
HubPresses hands a computer the presses and replies waiting for it, waiting up to wait for one when none is. Each is handed over once: a press lost on the way is lost, never acted on twice (a reply typed in twice is worse than one the owner sends again).
func (*Bridge) HubResult ¶ added in v0.200.0
HubResult shows what a computer did with a press: the message's buttons replaced by the outcome, a line under the reply, a 👍 on it.
func (*Bridge) QueuedSent ¶ added in v0.137.0
QueuedSent is the message queue typing a held forward in: its picker says it went.
func (*Bridge) ReplyOnce ¶ added in v0.137.0
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
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) Routing ¶ added in v0.200.0
Routing reports whether this machine's messages go through another computer's bot.
func (*Bridge) SendModule ¶ added in v0.147.0
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) SendNow ¶ added in v0.200.0
SendNow sends one message and waits for its outcome: through this machine's own bot, or handed to the holder (where an unreachable holder keeps it queued and the error says so).
func (*Bridge) SendPhoto ¶ added in v0.122.0
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 ¶
StartPairing makes a new code; the first private chat to send it becomes the bridge's only chat.
func (*Bridge) TakeOver ¶ added in v0.200.0
TakeOver makes this machine the bot's holder with what the old holder handed over: the token, the chat and the offset, so nothing is read twice and no new pairing is needed. from names the old holder in the chat.
func (*Bridge) TakeReplyOnce ¶ added in v0.137.0
TakeReplyOnce reports, once, that a session's answer was asked for.
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 Candidate ¶ added in v0.200.0
type Candidate struct {
ID string `json:"id"`
Name string `json:"name"`
Holder bool `json:"holder"`
BotUsername string `json:"bot_username,omitempty"`
ChatName string `json:"chat_name,omitempty"`
// Error is why it could not be asked: offline, not allowed there yet.
Error string `json:"error,omitempty"`
}
Candidate is one computer this machine reaches, as Settings → Telegram lists them for "send through": whether it holds a bot, and which.
type CarriedView ¶ added in v0.200.0
CarriedView is a computer that sends through this machine's bot.
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 ¶
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.
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 ¶
AnswerCallbackQuery stops a pressed button's spinner, with an optional toast.
func (*Client) Call ¶
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
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 ¶
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) React ¶
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 ¶
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 ¶
SetCommands sets the menu Telegram shows under "/" in the bot's chat.
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 Handover ¶ added in v0.200.0
type Handover struct {
Token string `json:"token"`
ChatID string `json:"chat_id"`
ChatName string `json:"chat_name,omitempty"`
BotID int64 `json:"bot_id,omitempty"`
BotUsername string `json:"bot_username,omitempty"`
Offset int64 `json:"offset,omitempty"`
}
Handover is the bot moving to the computer that asked: everything it needs to carry on where this machine stops, without a new bot or a new pairing. It crosses only the end-to-end encrypted link (ADR-067).
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 Hub ¶ added in v0.200.0
type Hub interface {
HubInfo() HubInfo
HubPost(ctx context.Context, s Sender, m HubMessage) (int64, error)
HubPresses(ctx context.Context, s Sender, wait time.Duration) []HubPress
HubResult(ctx context.Context, s Sender, r HubResult) error
Handover(ctx context.Context, s Sender) (Handover, error)
}
Hub is the holder's half as the routes need it; *Bridge is one.
type HubButton ¶ added in v0.200.0
type HubButton struct {
Text string `json:"text"`
Action string `json:"action,omitempty"`
URL string `json:"url,omitempty"`
}
HubButton is one button under a message from another computer: an action the holder hands back on a press, or a URL Telegram opens.
type HubClient ¶ added in v0.200.0
HubClient calls a holder's hub routes; Do carries one request to it (peers.Manager.Do with the holder's id, in the daemon).
type HubInfo ¶ added in v0.200.0
type HubInfo struct {
Holder bool `json:"holder"`
BotUsername string `json:"bot_username,omitempty"`
ChatName string `json:"chat_name,omitempty"`
}
HubInfo is whether this machine holds a bot another computer can send through.
type HubMessage ¶ added in v0.200.0
type HubMessage struct {
// ID is the sender's own id for it (at most 64 characters): what a press
// coming back names, and what makes a repeated post a no-op.
ID string `json:"id"`
// Text is the message; HTML when ParseMode is "HTML", else plain.
Text string `json:"text"`
ParseMode string `json:"parse_mode,omitempty"`
// Buttons are rows of buttons under it.
Buttons [][]HubButton `json:"buttons,omitempty"`
// Reply says a Telegram reply to it is carried back as ActReply.
Reply bool `json:"reply,omitempty"`
// LateS is how many seconds it waited on the sender for the holder;
// shown when a minute or more.
LateS int64 `json:"late_s,omitempty"`
}
HubMessage is one message another computer asks the holder to post.
func ToHub ¶ added in v0.200.0
func ToHub(m Out, id string, reply bool) HubMessage
ToHub is a message as the holder takes it: the text as it is, the alert's buttons as actions (Approve "y", Deny "n", Mute "m") and URLs, any other button dropped. reply says a Telegram reply to it is carried back (it is about a session).
type HubPress ¶ added in v0.200.0
type HubPress struct {
// ID is the message's id on the sender (HubMessage.ID).
ID string `json:"id"`
Action string `json:"action"`
// Text is a reply's words.
Text string `json:"text,omitempty"`
// Reply is the holder's Telegram message an outcome is threaded under
// (the reply itself); opaque to the sender, handed back in HubResult.
Reply int64 `json:"reply,omitempty"`
At int64 `json:"at"`
}
HubPress is a button pressed, or a reply sent, under a message from another computer, waiting for that computer to take it.
type HubResult ¶ added in v0.200.0
type HubResult struct {
ID string `json:"id"`
// Label replaces the message's buttons ("✅ Approved from Telegram").
Label string `json:"label,omitempty"`
// Say is a line threaded under the reply, or under the message.
Say string `json:"say,omitempty"`
// React puts a 👍 on the reply: it reached its session.
React bool `json:"react,omitempty"`
Reply int64 `json:"reply,omitempty"`
}
HubResult is what the sender did with a press, for the chat.
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
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.
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
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.
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).
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"`
// One bot for several computers (hub.go, ADR-047 amended 2026-11-27).
// On the holder, a "hub" message posted for another computer: Machine
// is that computer's device id here, MachineName its name, Remote the
// id that computer gave the message, Actions its buttons' actions by
// index (the callback data is "h:<index>"), and HubReply that a reply
// to it is carried back. On a computer that sends through a holder,
// Remote is the id of a message it handed over (MessageID 0): what a
// press coming back is about.
Remote string `json:"remote,omitempty"`
Machine string `json:"machine,omitempty"`
MachineName string `json:"machine_name,omitempty"`
Actions []string `json:"actions,omitempty"`
HubReply bool `json:"hub_reply,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 Sender ¶ added in v0.200.0
type Sender struct {
ID string
Name string
// Key is the relay key its token is bound to (pairing.Device.Key),
// which is its id in this machine's own machines.json if this machine
// reaches it too.
Key string
}
Sender is the computer a hub request came from, as the holder knows it: its device id and name in this machine's devices.json, never what the request says about itself.
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"`
// Carries are the other computers that post through this machine's
// bot, by their device id here: their name and when they last did
// (hub.go). MovedTo is set when the bot was handed to another computer:
// its name and when, so Settings says where the bot went.
Carries map[string]Carried `json:"carries,omitempty"`
MovedTo *Moved `json:"moved_to,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"`
// Via is the holder this machine sends through, when it has no bot of
// its own (hub.go); Carries the other computers that send through this
// machine's bot; MovedTo where this machine's bot went.
Via *ViaStatus `json:"via,omitempty"`
Carries []CarriedView `json:"carries,omitempty"`
MovedTo *Moved `json:"moved_to,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 ¶
OpenStore reads dir's state file; a missing or unreadable one is an empty state (the bridge relearns everything it holds).
func (*Store) LookupRemote ¶ added in v0.200.0
LookupRemote finds a message by the id it was handed over under: on a computer that sends through a holder, machine is "" and remote the id this machine gave it; on the holder, machine is the sender's device id here.
func (*Store) NextAnswer ¶ added in v0.147.0
NextAnswer counts one more answer to a sent message and returns the count.
func (*Store) Remember ¶
Remember records what a sent message is about: one sent here (MessageID), or one handed to the holder (Remote).
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.
type ViaStatus ¶ added in v0.200.0
type ViaStatus struct {
// Machine is the holder's id among the computers this one reaches;
// Name what this machine calls it.
Machine string `json:"machine"`
Name string `json:"name"`
// Queued is how many messages wait for it; Waiting says the last try to
// reach it failed, LastError in whose words.
Queued int `json:"queued"`
Waiting bool `json:"waiting,omitempty"`
LastError string `json:"last_error,omitempty"`
// LastSentMs is when it last took a message (unix ms, this clock).
LastSentMs int64 `json:"last_sent_ms,omitempty"`
// Dropped counts messages that waited past the queue's bounds since
// this daemon started.
Dropped int `json:"dropped,omitempty"`
}
ViaStatus is how Settings shows a computer that sends through a holder.
Source Files
¶
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. |