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 NewCode() (string, error)
- func StartLink(bot, code string) string
- func TooLarge(err error) bool
- func Unauthorized(err error) bool
- type APIError
- type Bridge
- func (b *Bridge) Active() 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) 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) Run(ctx context.Context)
- 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) TakeReplyOnce(id string) bool
- func (b *Bridge) Wake()
- type CallbackQuery
- 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) 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
- type Command
- type FileRef
- type ForceReply
- type ForwardOrigin
- type Host
- type InlineButton
- type Live
- type Markup
- type Message
- type Out
- type Outbox
- type Pairing
- type PhotoSize
- type Poller
- type Project
- type Ref
- type Send
- type State
- type Status
- type Store
- type Update
- type User
Constants ¶
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 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 ErrNoToken = errors.New("telegram: no bot token")
ErrNoToken is a call made with no token at all.
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 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
// 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) Active ¶
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 ¶
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.
func (*Bridge) Disconnect ¶
Disconnect forgets the bot, the chat and everything learned about them.
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) 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) 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 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.
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)
// 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
}
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 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 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"`
}
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"`
// 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 ¶
OpenStore reads dir's state file; a missing or unreadable one is an empty state (the bridge relearns everything it holds).
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.
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. |