notifybots

package
v0.16.16 Latest Latest
Warning

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

Go to latest
Published: Oct 28, 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 notifybots keeps the Telegram bots the person linked in Settings for notifications: each bot with its token, the chat it writes to and the person's instruction of when an agent should use it. The runtime holds the tokens and makes every call to Telegram; the page and the agents see a bot by its name, never its token.

Index

Constants

View Source
const (
	MaxName        = 64
	MaxInstruction = 2000
	// BindFor is how long a binding waits for the person's /start.
	BindFor = 10 * time.Minute
	// SendsPerMinute is how many messages an agent may send through one bot in a minute.
	SendsPerMinute = 20
)

Limits of the person's input and of the agents' sends.

View Source
const (
	ReasonBadToken       = "bad-token"       // the text is not shaped like a bot token
	ReasonDuplicate      = "duplicate"       // this bot is linked already
	ReasonNotFound       = "not-found"       // no bot of that id or name
	ReasonAmbiguous      = "ambiguous"       // the name matches more than one bot
	ReasonNotBound       = "not-bound"       // the bot has no chat yet
	ReasonEmpty          = "empty"           // nothing to send
	ReasonTooLong        = "too-long"        // more than MaxText characters
	ReasonBadName        = "bad-name"        // a name that is empty or too long
	ReasonBadInstruction = "bad-instruction" // an instruction that is too long
	ReasonFailed         = "failed"          // the file could not be read or written
)

Reasons of a refusal that is this runtime's own.

View Source
const (
	ReasonNotLinked = "not-linked" // the person has not connected Telegram yet
	ReasonNoShared  = "no-shared"  // no shared bot here: the cloud has none or cannot be reached
	ReasonOffline   = "offline"    // the cloud did not answer
	ReasonDisabled  = "disabled"   // own bots are switched off while the shared bot is on
	ReasonExpired   = "expired"    // the one-time code is not (or no longer) the one waiting
)

Reasons of the shared bot.

View Source
const (
	OwnBotsAuto = "auto"
	OwnBotsOn   = "on"
	OwnBotsOff  = "off"
)

Own bots by token, as RUNTIME_NOTIFY_OWN_BOTS says: on always, off never, auto (the default) only while there is no shared bot.

View Source
const (
	ReasonInvalidToken = "invalid-token" // Telegram does not know the token
	ReasonWebhook      = "webhook"       // the bot has a webhook: getUpdates is not allowed
	ReasonChatGone     = "chat-gone"     // the bot was removed from the chat or blocked by the person
	ReasonRateLimited  = "rate-limited"  // Telegram or this runtime asked to wait
	ReasonUnreachable  = "unreachable"   // no answer from Telegram
	ReasonRejected     = "rejected"      // Telegram refused the call for another reason
)

Reasons a call to Telegram fails, as the page and the agents are told them.

View Source
const CloudRoute = "/notify/call"

CloudRoute is the machine agent's loopback route that carries a call to the cloud (internal/agent/notifyrelay.go).

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

DefaultAPI is Telegram's Bot API.

View Source
const File = "notify-bots.json"

File is the bots' file in the runtime's v2 data folder.

View Source
const LocalFile = "notify-shared-local.json"

LocalFile keeps the person's chat with the installation's own shared bot (self-hosted, RUNTIME_NOTIFY_BOT_TOKEN).

View Source
const MaxText = 16000

MaxText is the longest text an agent may send at once (a few messages).

View Source
const MessageLimit = 4096

MessageLimit is Telegram's longest message text, in characters after the entities are parsed; the HTML of a part is kept under it so that its visible text always is.

View Source
const SharedCacheFile = "notify-shared.json"

SharedCacheFile keeps the shared bot's state as last seen, for the agents' prompt and for a page while the cloud is away.

Variables

View Source
var ErrNoAgent = errNoCloud

ErrNoAgent is what Cloud.Call returns when no machine agent runs for this account: there is no cloud to ask.

View Source
var ErrNotFound = errors.New("notifybots: no such bot")

ErrNotFound: no bot has that id.

Functions

func CleanToken

func CleanToken(s string) string

CleanToken is a pasted token without the spaces and quotes around it.

func HasCode

func HasCode(text, code string) bool

HasCode says whether a message carries the code: "/start <code>", "/start@bot <code>" or the code alone.

func Label

func Label(s string) string

Label is a name from outside (a Telegram chat's title) as it may be shown and put into a prompt: one line of printable characters, at most 64 of them.

func OwnBotsAllowed

func OwnBotsAllowed(mode string, sharedEnabled bool) bool

OwnBotsAllowed says whether the person may link and use bots of their own.

func PromptBlock

func PromptBlock(bots []Bot) string

PromptBlock is the part of an agent's system prompt about the bots: those with a chat, each with its instruction; "" when there are none.

func ReasonOf

func ReasonOf(err error) string

ReasonOf is the reason of a failed call; "" for an error that is not one.

func SharedCachePath

func SharedCachePath(dataDir string) string

SharedCachePath is the cache's place in a runtime's data folder.

func SharedPromptBlock

func SharedPromptBlock(st SharedState) string

SharedPromptBlock is the part of an agent's system prompt about the person's Telegram; "" until it is connected.

func Split

func Split(text string, limit int) []string

Split cuts a text into parts whose HTML stays under the limit: at blank lines, then at lines, then at spaces, and a word longer than a message is cut where it has to be.

func ToHTML

func ToHTML(text string) string

ToHTML is the agent's markdown-ish text as Telegram HTML: everything escaped, then **bold**, `code`, ```blocks```, [links](https://…) and # headings made into the few tags Telegram takes. Whatever else is left as written.

Types

type APIError

type APIError struct {
	Reason string
	// Detail is Telegram's own description (or the network error without the address).
	Detail string
	// RetryAfter is Telegram's wait in seconds, MigrateTo a group's new id after it became a supergroup.
	RetryAfter int
	MigrateTo  int64
}

APIError is a failed call to Telegram. Its text never holds the token: the request's address is never part of it.

func (*APIError) Error

func (e *APIError) Error() string

type AgentBot

type AgentBot struct {
	ID          string `json:"id"`
	Name        string `json:"name"`
	Username    string `json:"username"`
	Chat        string `json:"chat"`
	Bound       bool   `json:"bound"`
	Instruction string `json:"instruction"`
}

AgentBot is a bot as an agent sees it: what it is called, where it writes and when to use it.

type Backend

type Backend interface {
	State(ctx context.Context) (SharedState, error)
	Link(ctx context.Context) (SharedState, error)
	Unlink(ctx context.Context) (SharedState, error)
	SetInstruction(ctx context.Context, text string) (SharedState, error)
	Send(ctx context.Context, parts []Part, silent bool) (SharedSent, error)
}

Backend is where the shared bot lives: the cloud (Cloud) or this runtime (Local).

type Binding

type Binding struct {
	Code      string
	ExpiresAt time.Time
	// Failed is why the wait stopped without a chat ("" while it waits).
	Failed string
	// contains filtered or unexported fields
}

Binding is a wait for the person's /start with a one-time code.

type BindingView

type BindingView struct {
	State string `json:"state"` // waiting | failed
	Code  string `json:"code"`
	// Link opens the bot with the code; Command is what to send in a group.
	Link      string `json:"link"`
	Command   string `json:"command"`
	ExpiresAt int64  `json:"expiresAt"`
	Reason    string `json:"reason"`
}

BindingView is a binding in progress, or how it ended.

type Bot

type Bot struct {
	ID string `json:"id"`
	// Name is the person's name for it, the one agents pick it by.
	Name string `json:"name"`
	// Username and Title are the bot's @username and its display name as getMe said.
	Username string `json:"username"`
	Title    string `json:"title"`
	// TelegramID is the bot's own user id: a new token of the same bot keeps the chat.
	TelegramID int64  `json:"telegramId"`
	Token      string `json:"token"`
	// Chat is where the bot writes; nil until a chat is bound.
	Chat        *Chat  `json:"chat,omitempty"`
	Instruction string `json:"instruction"`
	CreatedAt   int64  `json:"createdAt"`
	UpdatedAt   int64  `json:"updatedAt"`
}

Bot is one linked bot as it is stored.

type Button

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

Button is one inline keyboard button; Data comes back in the press (64 bytes at most, Telegram's limit).

type CallbackQuery

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

CallbackQuery is a press of an inline button.

type Change

type Change struct {
	Name        *string `json:"name"`
	Instruction *string `json:"instruction"`
	// Token replaces the token; another bot's token forgets the chat (that bot has not been added to it).
	Token *string `json:"token"`
}

Change is an edit of a bot from the page; nil fields stay as they are.

type Chat

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

Chat is the bound chat: a private chat with the person, a group or a channel.

type ChatView

type ChatView struct {
	Title string `json:"title"`
	Type  string `json:"type"`
}

ChatView is the bound chat without its id.

type Client

type Client struct {
	// Base is the API's address (DefaultAPI when empty); tests put a fake server here.
	Base string
	HTTP *http.Client
}

Client calls the Bot API.

func (*Client) AnswerCallback

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

AnswerCallback acknowledges a button press, with a short toast for the one who pressed it when text is set.

func (*Client) EditHTML

func (c *Client) EditHTML(ctx context.Context, token string, chat, message int64, html string) error

EditHTML replaces a message's text and drops its buttons.

func (*Client) GetFullUpdates

func (c *Client) GetFullUpdates(ctx context.Context, token string, offset int64, wait time.Duration) ([]FullUpdate, error)

GetFullUpdates waits up to wait for messages and button presses after offset.

func (*Client) GetMe

func (c *Client) GetMe(ctx context.Context, token string) (Me, error)

GetMe checks a token: the bot it belongs to.

func (*Client) GetUpdates

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

GetUpdates waits up to wait for new messages after offset.

func (*Client) SendHTML

func (c *Client) SendHTML(ctx context.Context, token string, chat int64, html string, rows [][]Button, silent bool) (int64, error)

SendHTML sends one Telegram-HTML message, with rows of inline buttons when given, and returns its message id.

func (*Client) SendMessage

func (c *Client) SendMessage(ctx context.Context, token string, chat int64, text string, html, silent bool) error

SendMessage sends one message; html says the text is Telegram HTML.

type Cloud

type Cloud struct {
	// Call posts a body to the agent's loopback route and returns its status and body (agent.CallLocal); it returns
	// ErrNoAgent (or an error wrapping it) when the account has no agent.
	Call func(route string, body any) (int, []byte, error)
}

Cloud is the cloud's shared bot, reached through the machine agent: the cloud knows the person by the machine's link and holds the bot's token and the person's chat; this side holds neither.

func (c *Cloud) Link(ctx context.Context) (SharedState, error)

func (*Cloud) Send

func (c *Cloud) Send(ctx context.Context, parts []Part, silent bool) (SharedSent, error)

func (*Cloud) SetInstruction

func (c *Cloud) SetInstruction(ctx context.Context, text string) (SharedState, error)

func (*Cloud) State

func (c *Cloud) State(ctx context.Context) (SharedState, error)
func (c *Cloud) Unlink(ctx context.Context) (SharedState, error)

type FullMessage

type FullMessage struct {
	MessageID int64  `json:"message_id"`
	Date      int64  `json:"date"`
	Text      string `json:"text"`
	Caption   string `json:"caption"`
	From      *User  `json:"from"`
	Chat      struct {
		ID    int64  `json:"id"`
		Type  string `json:"type"`
		Title string `json:"title"`
	} `json:"chat"`
	ReplyTo *struct {
		MessageID int64 `json:"message_id"`
		From      *User `json:"from"`
	} `json:"reply_to_message"`
}

FullMessage is a message with what a reply is matched by: its id, its sender and the message it replies to.

type FullUpdate

type FullUpdate struct {
	UpdateID      int64          `json:"update_id"`
	Message       *FullMessage   `json:"message"`
	CallbackQuery *CallbackQuery `json:"callback_query"`
}

FullUpdate is an update with messages and button presses.

type Local

type Local struct {
	Token    string
	Telegram *Client
	// Path is LocalFile in the runtime's v2 data folder.
	Path string
	Now  func() time.Time
	// The bot's answers: to a /start with the code, to /stop, and to anything else.
	Linked, Stopped, Hello string
	// Log is told of a poll that cannot go on (a webhook on the bot, a token Telegram does not know).
	Log func(reason string)
	// contains filtered or unexported fields
}

Local is the shared bot of a self-hosted runtime: its token is in the runtime's configuration, the runtime reads the bot's messages all the time (a /start with the code links the chat, /stop forgets it) and sends itself.

func (l *Local) Link(ctx context.Context) (SharedState, error)

func (*Local) Run

func (l *Local) Run(ctx context.Context)

Run reads the bot's messages until ctx ends.

func (*Local) Send

func (l *Local) Send(ctx context.Context, parts []Part, silent bool) (SharedSent, error)

func (*Local) SetInstruction

func (l *Local) SetInstruction(ctx context.Context, text string) (SharedState, error)

func (*Local) State

func (l *Local) State(ctx context.Context) (SharedState, error)
func (l *Local) Unlink(ctx context.Context) (SharedState, error)

type Me

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

Me is getMe's answer.

type Message

type Message struct {
	Text string `json:"text"`
	Chat struct {
		ID        int64  `json:"id"`
		Type      string `json:"type"`
		Title     string `json:"title"`
		Username  string `json:"username"`
		FirstName string `json:"first_name"`
		LastName  string `json:"last_name"`
	} `json:"chat"`
}

Message is a message of an update.

type Part

type Part struct {
	HTML string `json:"html"`
	Text string `json:"text"`
}

Part is one message of a send: Telegram HTML, and the same text plain for when Telegram cannot parse the HTML.

func Parts

func Parts(text string) ([]Part, error)

Parts is the agent's markdown-ish text as the messages to send.

type Refusal

type Refusal struct {
	Reason string
	Detail string
}

Refusal is a reason the caller is told, with Telegram's own words when it has them.

func RefusalOf

func RefusalOf(err error) Refusal

RefusalOf is what to tell the caller of any error of the service.

func (*Refusal) Error

func (r *Refusal) Error() string

type Sent

type Sent struct {
	Bot      string `json:"bot"`
	Chat     string `json:"chat"`
	Messages int    `json:"messages"`
}

Sent is what a send did.

type Service

type Service struct {
	Store    *Store
	Telegram *Client
	Now      func() time.Time
	// Confirm is the message the bot writes to a chat once it is bound.
	Confirm string
	// contains filtered or unexported fields
}

Service is the bots of this runtime: the page links and edits them, the agents list and send.

func (*Service) Add

func (s *Service) Add(ctx context.Context, token, name, instruction string) (View, error)

Add links a bot by its token: Telegram says whose it is. The name is the bot's own when none is given.

func (*Service) AgentBots

func (s *Service) AgentBots() ([]AgentBot, error)

AgentBots are every bot for `harnessly notify list`.

func (*Service) Edit

func (s *Service) Edit(ctx context.Context, id string, c Change) (View, error)

Edit changes a bot's name, instruction or token.

func (*Service) Find

func (s *Service) Find(ref string) (Bot, error)

Find is a bot by its id, its name (any case) or its @username.

func (*Service) Remove

func (s *Service) Remove(id string) error

Remove unlinks a bot: its token is gone from the machine.

func (*Service) Send

func (s *Service) Send(ctx context.Context, ref, text string, silent bool) (Sent, error)

Send writes the text to the bot's chat, as several messages when it is long. The text is the agent's markdown-ish text; a part Telegram cannot parse as HTML goes as plain text.

func (*Service) StartBinding

func (s *Service) StartBinding(id string) (View, error)

StartBinding makes a new one-time code for the bot and waits in the background, up to BindFor, for a message with it.

func (*Service) StopBinding

func (s *Service) StopBinding(id string)

StopBinding ends a bot's wait, if it has one.

func (*Service) Test

func (s *Service) Test(ctx context.Context, id, text string) (Sent, error)

Test sends the page's test message.

func (*Service) ViewOf

func (s *Service) ViewOf(id string) (View, error)

ViewOf is one bot for the page.

func (*Service) Views

func (s *Service) Views() ([]View, error)

Views are every bot for the page.

type Shared

type Shared struct {
	// Backend is nil when there is no shared bot to reach at all.
	Backend Backend
	// CachePath is SharedCacheFile in the runtime's v2 data folder.
	CachePath string
	// contains filtered or unexported fields
}

Shared is the shared bot of this runtime: its backend and the cache of what it last said.

func (*Shared) Cached

func (s *Shared) Cached() SharedState

Cached is the state last seen.

func (s *Shared) Link(ctx context.Context) (SharedState, error)

Link makes a new one-time code: the state carries the link that opens the bot with it.

func (*Shared) RefreshSoon

func (s *Shared) RefreshSoon(every time.Duration)

RefreshSoon asks the backend in the background, at most once per every, so that the cache follows a change made on another machine or in the bot (/stop).

func (*Shared) Send

func (s *Shared) Send(ctx context.Context, text string, silent bool) (SharedSent, error)

Send writes the text to the person's chat through the shared bot.

func (*Shared) SetInstruction

func (s *Shared) SetInstruction(ctx context.Context, text string) (SharedState, error)

SetInstruction keeps the person's instruction of when agents write.

func (*Shared) State

func (s *Shared) State(ctx context.Context) (SharedState, error)

State asks the backend; when it cannot be asked the cached state comes back with the error.

func (s *Shared) Unlink(ctx context.Context) (SharedState, error)

Unlink forgets the person's chat; the instruction stays for the next one.

type SharedBinding

type SharedBinding struct {
	Link      string `json:"link"`
	ExpiresAt int64  `json:"expiresAt"`
}

SharedBinding is a one-time code waiting for the person's Start: the link opens the bot with it.

type SharedChat

type SharedChat struct {
	Title string `json:"title"`
}

SharedChat is the person's chat: its title only, made one plain line (it comes from Telegram).

type SharedSent

type SharedSent struct {
	Chat     string `json:"chat"`
	Messages int    `json:"messages"`
}

SharedSent is what a send through the shared bot did.

type SharedState

type SharedState struct {
	// Enabled: there is a shared bot here; everything else is empty when there is not.
	Enabled     bool           `json:"enabled"`
	Bot         string         `json:"bot"`
	Chat        *SharedChat    `json:"chat"`
	Instruction string         `json:"instruction"`
	Binding     *SharedBinding `json:"binding"`
}

SharedState is the person's Telegram as the page and the agents see it.

func ReadSharedCache

func ReadSharedCache(path string) SharedState

ReadSharedCache is the state last seen, or nothing enabled.

type Store

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

Store reads and writes the bots' file; every writer of this process goes through one Store.

func Open

func Open(dataDir string) *Store

Open is the process's one Store of a data folder's file (the routes and the agents' launch share it).

func (*Store) Add

func (s *Store) Add(b Bot) error

Add appends a new bot.

func (*Store) Get

func (s *Store) Get(id string) (Bot, error)

Get is one bot by id.

func (*Store) List

func (s *Store) List() ([]Bot, error)

List is every bot in the order they were added.

func (*Store) Remove

func (s *Store) Remove(id string) error

Remove drops one bot.

func (*Store) Update

func (s *Store) Update(id string, change func(*Bot) error) (Bot, error)

Update changes one bot under the lock and writes it back; the changed bot is returned.

type Update

type Update struct {
	UpdateID    int64    `json:"update_id"`
	Message     *Message `json:"message"`
	ChannelPost *Message `json:"channel_post"`
}

Update is the part of an update the binding reads.

type User

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

User is the sender of a message or of a button press.

type View

type View struct {
	ID          string       `json:"id"`
	Name        string       `json:"name"`
	Username    string       `json:"username"`
	Title       string       `json:"title"`
	TokenSet    bool         `json:"tokenSet"`
	TokenTail   string       `json:"tokenTail"`
	Chat        *ChatView    `json:"chat"`
	Instruction string       `json:"instruction"`
	Binding     *BindingView `json:"binding"`
	CreatedAt   int64        `json:"createdAt"`
	UpdatedAt   int64        `json:"updatedAt"`
}

View is a bot as the page sees it: never its token, only that one is set and its last characters.

Jump to

Keyboard shortcuts

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