telegram

package
v0.1.0-beta.1 Latest Latest
Warning

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

Go to latest
Published: Nov 10, 2026 License: Apache-2.0 Imports: 31 Imported by: ? 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 a notification channel on each person's own Telegram bot: it tells them what waits on them, lets them answer with buttons, and reports their runs.

It is built to do little, on purpose. A Telegram account is easier to lose than a laptop, and the agents it talks to may run code, so:

  • The only thing it can change is the answer to a task that waits on the bot's owner, and only with buttons: approve or reject an approval, pick options of a form (lagrange/ask). It never starts, cancels or messages anything, and typed text is never sent anywhere. Deps is the whole of what it can reach.
  • It listens to one private chat and one Telegram user, bound by a one-time pairing code; everything else gets no answer at all.
  • Buttons carry random tokens that name rows here, never tasks. Closing the message is the claim that lets one answer through; the answer then goes through the same checks as the inbox.
  • Approving asks twice.
  • The bot token only ever goes to api.telegram.org, and never appears in errors, logs or the API.

Bots long-poll (getUpdates), so a server needs no public URL. One replica polls each bot, under a Postgres advisory lock.

Index

Constants

View Source
const (
	// LevelQuestions sends only what waits on the person.
	LevelQuestions = "questions"
	// LevelMilestones also sends report notices and finished runs.
	LevelMilestones = "milestones"
)

Levels: what a bot sends besides questions.

View Source
const ButtonTTL = 7 * 24 * time.Hour

ButtonTTL is how long buttons work.

View Source
const PairTTL = 10 * time.Minute

PairTTL is how long a pairing code works.

Variables

View Source
var ErrBadToken = errors.New("that isn't a working bot token: copy the whole token @BotFather sent (digits, a colon, then letters)")

ErrBadToken means the token isn't a bot token, or Telegram doesn't know it.

View Source
var ErrGone = errors.New("the task no longer waits for this answer")

ErrGone means the task no longer waits for this answer (answered elsewhere, canceled, or not the person's to answer).

Functions

func Dur

func Dur(d time.Duration) string

Dur is a duration in a few characters: "45s", "14m", "2h05m", "3d".

func IsUserError

func IsUserError(err error) bool

IsUserError reports whether err is the person's to fix (a bad token, a bot that is someone else's), not the server's.

func ValidToken

func ValidToken(s string) bool

ValidToken reports whether s looks like a bot token from @BotFather.

Types

type Answer

type Answer struct {
	Decision string
	Text     string
}

Answer is an answer from a button: a decision ("approve" or "reject") or a form's text, never typed text.

type Button

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

Button is an inline keyboard button.

type CallbackQuery

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

CallbackQuery is a button press.

type Chat

type Chat struct {
	ID   int64  `json:"id"`
	Type string `json:"type"`
}

Chat is a Telegram chat.

type Deps

type Deps struct {
	// Answer answers a task waiting on handle, with the inbox's checks. It returns
	// ErrGone when the task doesn't wait for this answer anymore.
	Answer func(ctx context.Context, handle, taskID string, a Answer) error
	// Waiting lists the tasks waiting on handle.
	Waiting func(ctx context.Context, handle string) ([]Waiting, error)
	// Runs lists handle's latest runs, newest first.
	Runs func(ctx context.Context, handle string, limit int) ([]Run, error)
	// Run returns the run rooted at taskID, if handle sees it.
	Run func(ctx context.Context, handle, taskID string) (*Run, error)
}

Deps is everything the bot can reach beyond its own tables: one way to answer and three read-only queries, each on behalf of one person. Nothing here starts, cancels or sends a message, and nothing should be added that does.

type Keyboard

type Keyboard [][]Button

Keyboard is rows of buttons.

type Message

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

Message is a Telegram message.

type Run

type Run struct {
	ID    string
	Title string
	// State is the root task's state; Status the run's group (running, waiting, done, failed).
	State, Status string
	Waiting       []string
	Cost          float64
	Currency      string
	StartedAt     time.Time
	UpdatedAt     time.Time
	Outcome       string
	Report        *report.Report
}

Run is a run, as Telegram shows it.

type Service

type Service struct {
	DB        *pg.DB
	Directory *directory.Directory
	Activity  *activity.Log
	// PublicURL is the server's base URL, for links.
	PublicURL string
	Deps      Deps
	// HTTP calls the Bot API (default: a client with a 70s timeout).
	HTTP   *http.Client
	Logger *slog.Logger
	// PollTimeout is getUpdates' long-poll timeout (default 50s).
	PollTimeout time.Duration
	// Rescan is how often the bot list is read again (default 30s); Kick does it now.
	Rescan time.Duration
	// Tick is how often the activity log is followed (default 1s).
	Tick time.Duration
	// MinRun is how long a run without a report must have taken for its end to be
	// worth a message (default 1m); failed runs and runs with a report always are.
	MinRun time.Duration
	// APIBase replaces https://api.telegram.org. Tests only: it is never set from
	// configuration or input.
	APIBase string
	// Now is the clock (tests).
	Now func() time.Time
	// contains filtered or unexported fields
}

Service runs every person's bot.

func (*Service) Connect

func (s *Service) Connect(ctx context.Context, u *directory.User, token string) (*Status, error)

Connect checks a bot token with Telegram, connects the bot to u (replacing any other), and starts pairing.

func (*Service) Disconnect

func (s *Service) Disconnect(ctx context.Context, u *directory.User) error

Disconnect removes u's bot. The bot itself stays theirs in Telegram.

func (*Service) Kick

func (s *Service) Kick()

Kick reads the bot list again now (after a bot is connected or removed).

func (*Service) Notice

func (s *Service) Notice(ctx context.Context, u *directory.User, nt notify.Notice) (bool, error)

Notice sends a notice about a waiting task to the person's bot (notify.Channel).

func (*Service) Pair

func (s *Service) Pair(ctx context.Context, u *directory.User) (*Status, error)

Pair makes a new pairing code for u's bot and returns the link that sends it.

func (*Service) Run

func (s *Service) Run(ctx context.Context)

Run polls every bot and follows the activity log until ctx ends.

func (*Service) SetLevel

func (s *Service) SetLevel(ctx context.Context, u *directory.User, level string) (*Status, error)

SetLevel sets what u's bot sends besides questions.

func (*Service) Status

func (s *Service) Status(ctx context.Context, u *directory.User) (*Status, error)

Status returns u's connection.

func (*Service) Test

func (s *Service) Test(ctx context.Context, u *directory.User) (bool, error)

Test sends a test message to the person's bot (notify.Channel).

type Status

type Status struct {
	Connected   bool   `json:"connected"`
	BotUsername string `json:"botUsername,omitempty"`
	Paired      bool   `json:"paired"`
	// ChatUsername is the Telegram user the bot is paired with.
	ChatUsername string `json:"chatUsername,omitempty"`
	// PairLink opens the bot with a fresh pairing code; only right after it is made.
	PairLink      string     `json:"pairLink,omitempty"`
	PairExpiresAt *time.Time `json:"pairExpiresAt,omitempty"`
	Level         string     `json:"level,omitempty"`
	MutedUntil    *time.Time `json:"mutedUntil,omitempty"`
}

Status is a person's Telegram connection, as the API shows it. It never has the token.

type Update

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

Update is one incoming update.

type User

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

User is a Telegram user (or bot).

type Waiting

type Waiting struct {
	TaskID, Asker, State string
	// For is who it waits on, when it isn't the person (it was escalated to them).
	For      string
	Question *a2a.Message
	Since    time.Time
}

Waiting is a task waiting on the person.

Jump to

Keyboard shortcuts

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