telegram

package
v0.107.4 Latest Latest
Warning

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

Go to latest
Published: Oct 11, 2026 License: Apache-2.0 Imports: 20 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, editMessageReplyMarkup, setMessageReaction, setMyCommands and answerCallbackQuery. 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 (
	// 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 (
	// 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 ErrNoToken = errors.New("telegram: no bot token")

ErrNoToken is a call made with no token at all.

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 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 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
	// 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) Muted

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

Muted reports whether a session sends nothing to Telegram.

func (*Bridge) Run

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

Run polls and sends until ctx ends.

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

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

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

type Command

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

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

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

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
}

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"`
}

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.

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 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"`
}

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"`
}

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

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