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
- Variables
- func CleanToken(s string) string
- func HasCode(text, code string) bool
- func Label(s string) string
- func OwnBotsAllowed(mode string, sharedEnabled bool) bool
- func PromptBlock(bots []Bot) string
- func ReasonOf(err error) string
- func SharedCachePath(dataDir string) string
- func SharedPromptBlock(st SharedState) string
- func Split(text string, limit int) []string
- func ToHTML(text string) string
- type APIError
- type AgentBot
- type Backend
- type Binding
- type BindingView
- type Bot
- type Button
- type CallbackQuery
- type Change
- type Chat
- type ChatView
- type Client
- func (c *Client) AnswerCallback(ctx context.Context, token, id, text string) error
- func (c *Client) Call(ctx context.Context, token, method string, body, out any) error
- func (c *Client) EditHTML(ctx context.Context, token string, chat, message int64, html string) error
- func (c *Client) GetFullUpdates(ctx context.Context, token string, offset int64, wait time.Duration) ([]FullUpdate, error)
- func (c *Client) GetMe(ctx context.Context, token string) (Me, error)
- func (c *Client) GetUpdates(ctx context.Context, token string, offset int64, wait time.Duration) ([]Update, error)
- func (c *Client) SendHTML(ctx context.Context, token string, chat int64, html string, rows [][]Button, ...) (int64, error)
- func (c *Client) SendMessage(ctx context.Context, token string, chat int64, text string, html, silent bool) error
- type Cloud
- func (c *Cloud) Link(ctx context.Context) (SharedState, error)
- func (c *Cloud) Send(ctx context.Context, parts []Part, silent bool) (SharedSent, error)
- func (c *Cloud) SetInstruction(ctx context.Context, text string) (SharedState, error)
- func (c *Cloud) State(ctx context.Context) (SharedState, error)
- func (c *Cloud) Unlink(ctx context.Context) (SharedState, error)
- type FullMessage
- type FullUpdate
- type Local
- func (l *Local) Link(ctx context.Context) (SharedState, error)
- func (l *Local) Run(ctx context.Context)
- func (l *Local) Send(ctx context.Context, parts []Part, silent bool) (SharedSent, error)
- func (l *Local) SetInstruction(ctx context.Context, text string) (SharedState, error)
- func (l *Local) State(ctx context.Context) (SharedState, error)
- func (l *Local) Unlink(ctx context.Context) (SharedState, error)
- type Me
- type Message
- type Part
- type Refusal
- type Sent
- type Service
- func (s *Service) Add(ctx context.Context, token, name, instruction string) (View, error)
- func (s *Service) AgentBots() ([]AgentBot, error)
- func (s *Service) Edit(ctx context.Context, id string, c Change) (View, error)
- func (s *Service) Find(ref string) (Bot, error)
- func (s *Service) Remove(id string) error
- func (s *Service) Send(ctx context.Context, ref, text string, silent bool) (Sent, error)
- func (s *Service) StartBinding(id string) (View, error)
- func (s *Service) StopBinding(id string)
- func (s *Service) Test(ctx context.Context, id, text string) (Sent, error)
- func (s *Service) ViewOf(id string) (View, error)
- func (s *Service) Views() ([]View, error)
- type Shared
- func (s *Shared) Cached() SharedState
- func (s *Shared) Link(ctx context.Context) (SharedState, error)
- func (s *Shared) RefreshSoon(every time.Duration)
- func (s *Shared) Send(ctx context.Context, text string, silent bool) (SharedSent, error)
- func (s *Shared) SetInstruction(ctx context.Context, text string) (SharedState, error)
- func (s *Shared) State(ctx context.Context) (SharedState, error)
- func (s *Shared) Unlink(ctx context.Context) (SharedState, error)
- type SharedBinding
- type SharedChat
- type SharedSent
- type SharedState
- type Store
- type Update
- type User
- type View
Constants ¶
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.
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.
const ( ReasonNotLinked = "not-linked" // the person has not connected Telegram yet 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.
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.
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.
const CloudRoute = "/notify/call"
CloudRoute is the machine agent's loopback route that carries a call to the cloud (internal/agent/notifyrelay.go).
const DefaultAPI = "https://api.telegram.org"
DefaultAPI is Telegram's Bot API.
const File = "notify-bots.json"
File is the bots' file in the runtime's v2 data folder.
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).
const MaxText = 16000
MaxText is the longest text an agent may send at once (a few messages).
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.
SharedCacheFile keeps the shared bot's state as last seen, for the agents' prompt and for a page while the cloud is away.
Variables ¶
var ErrNoAgent = errNoCloud
ErrNoAgent is what Cloud.Call returns when no machine agent runs for this account: there is no cloud to ask.
var ErrNotFound = errors.New("notifybots: no such bot")
ErrNotFound: no bot has that id.
Functions ¶
func CleanToken ¶
CleanToken is a pasted token without the spaces and quotes around it.
func HasCode ¶
HasCode says whether a message carries the code: "/start <code>", "/start@bot <code>" or the code alone.
func Label ¶
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 ¶
OwnBotsAllowed says whether the person may link and use bots of their own.
func PromptBlock ¶
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 SharedCachePath ¶
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.
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.
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 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 ¶
AnswerCallback acknowledges a button press, with a short toast for the one who pressed it when text is set.
func (*Client) Call ¶
Call posts any Bot API method with a JSON body and decodes its result into out (nil to drop it): for the callers that need updates or methods beyond the ones above (internal/connectors/telegram). Its errors are APIError.
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) 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.
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 (*Cloud) SetInstruction ¶
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 (*Local) SetInstruction ¶
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 ¶
Part is one message of a send: Telegram HTML, and the same text plain for when Telegram cannot parse the HTML.
type Refusal ¶
Refusal is a reason the caller is told, with Telegram's own words when it has them.
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 ¶
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) Send ¶
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 ¶
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 ¶
StopBinding ends a bot's wait, if it has one.
type Shared ¶
Shared is the shared bot of this runtime: its backend and the cache of what it last said.
func (*Shared) Link ¶
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 ¶
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) SetInstruction ¶
SetInstruction keeps the person's instruction of when agents write.
type SharedBinding ¶
type SharedBinding struct {
}
SharedBinding is a one-time code waiting for the person's Start: the link opens the bot with it.
type SharedChat ¶
type SharedChat struct {
}
SharedChat is the person's chat: its title only, made one plain line (it comes from Telegram).
type SharedState ¶
type SharedState struct {
// Enabled: there is a shared bot here; everything else is empty when there is not.
}
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 ¶
Open is the process's one Store of a data folder's file (the routes and the agents' launch share it).
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.