Documentation
¶
Overview ¶
Package botcomm is the official Go SDK for building BotComm bots.
A bot authenticates with its client credentials (client_credentials grant, re-granted automatically before the access token expires), keeps an SSE stream to /updates and receives incoming messages on the Messages and Commands channels. On every (re)connect the SDK back-fills unread messages via the REST API, so nothing is lost while the bot was offline. Replies go through Send/SendKeyboard, and Broadcast reaches every session at once. Typing, Edit and Delete update the conversation in place. RegisterSettings declares per-session settings the user edits in the app; changes arrive on the Settings channel. Rate-limited (429) requests are retried once after Retry-After. See examples/echo for a minimal bot.
Index ¶
- func SplitCommand(content string) (string, string)
- type Action
- type AgentCard
- type Attachment
- type Bot
- func (b *Bot) Broadcast(ctx context.Context, content string, silent ...bool) (*Broadcast, error)
- func (b *Bot) BroadcastKeyboard(ctx context.Context, content string, options []KeyboardOption) (*Broadcast, error)
- func (b *Bot) BroadcastStatus(ctx context.Context, id string) (*Broadcast, error)
- func (b *Bot) BroadcastWithOptions(ctx context.Context, content string, options SendOptions) (*Broadcast, error)
- func (b *Bot) Delete(ctx context.Context, sessionID, messageID string) error
- func (b *Bot) Edit(ctx context.Context, sessionID, messageID, content string, ...) (*Message, error)
- func (b *Bot) EditWithOptions(ctx context.Context, sessionID, messageID string, options EditOptions) (*Message, error)
- func (b *Bot) FeaturedBots(ctx context.Context) ([]*FeaturedBot, error)
- func (b *Bot) GetCardMessage(ctx context.Context, sessionID, messageID string) (*CardMessage, error)
- func (b *Bot) GetMessage(ctx context.Context, sessionID, messageID string) (*Message, error)
- func (b *Bot) React(ctx context.Context, sessionID, messageID, emoji string) (*Message, error)
- func (b *Bot) RecentMessages(ctx context.Context, sessionID string) ([]*Message, error)
- func (b *Bot) RegisterCollections(ctx context.Context, fields []CollectionField) error
- func (b *Bot) RegisterCommands(ctx context.Context, commands []*Command) error
- func (b *Bot) RegisterSettings(ctx context.Context, fields []SettingField) error
- func (b *Bot) RespondCollection(ctx context.Context, req *CollectionRequest, result CollectionResult) error
- func (b *Bot) Run(ctx context.Context, opts ...*Opts) error
- func (b *Bot) Send(ctx context.Context, sessionID, content string, silent ...bool) (*Message, error)
- func (b *Bot) SendCard(ctx context.Context, sessionID string, card AgentCard) (*CardMessage, error)
- func (b *Bot) SendKeyboard(ctx context.Context, sessionID, content string, options []KeyboardOption) (*Message, error)
- func (b *Bot) SendMessage(ctx context.Context, sessionID string, input MessageInput) (*Message, error)
- func (b *Bot) SendWithOptions(ctx context.Context, sessionID, content string, options SendOptions) (*Message, error)
- func (b *Bot) Sessions(ctx context.Context) ([]*Session, error)
- func (b *Bot) SetInputMode(ctx context.Context, mode string) error
- func (b *Bot) SetMessageAcceptor(accept func(context.Context, *Message) error)
- func (b *Bot) SetOnlineStatusVisible(ctx context.Context, visible bool) error
- func (b *Bot) SetSettings(ctx context.Context, sessionID string, values map[string]string) (*SessionSettings, error)
- func (b *Bot) StartStream(ctx context.Context, sessionID string) (*Message, error)
- func (b *Bot) Stop()
- func (b *Bot) Typing(ctx context.Context, sessionID string) error
- func (b *Bot) UpdateCard(ctx context.Context, sessionID, messageID string, change CardUpdate) (*CardMessage, error)
- func (b *Bot) UpdateMessage(ctx context.Context, sessionID, messageID string, change MessageUpdate) (*Message, error)
- func (b *Bot) UpdateStream(ctx context.Context, sessionID, messageID string, input StreamInput) (*Message, error)
- func (b *Bot) UploadAttachment(ctx context.Context, sessionID, name string, data []byte) (*Attachment, error)
- type Broadcast
- type CardAction
- type CardDetail
- type CardKind
- type CardMessage
- type CardTask
- type CardTaskStatus
- type CardUpdate
- type CollectionField
- type CollectionItem
- type CollectionRequest
- type CollectionResult
- type Command
- type CommandInput
- type EditOptions
- type Envelope
- type FeaturedBot
- type FormField
- type Keyboard
- type KeyboardOption
- type LinkPreview
- type Message
- type MessageInput
- type MessageStream
- type MessageUpdate
- type Opts
- func (o *Opts) SetArgumentCommands(enabled bool) *Opts
- func (o *Opts) SetCollections(fields []CollectionField) *Opts
- func (o *Opts) SetCommands(commands []*Command) *Opts
- func (o *Opts) SetInputMode(mode string) *Opts
- func (o *Opts) SetNewSession(callback func(session *Session)) *Opts
- func (o *Opts) SetOnlineStatusVisible(visible bool) *Opts
- func (o *Opts) SetSettings(fields []SettingField) *Opts
- type PreviewImage
- type ReadReceipt
- type SendOptions
- type Session
- type SessionSettings
- type SettingField
- type StreamInput
- type User
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func SplitCommand ¶
SplitCommand preserves the argument as one text value, including internal spaces.
Types ¶
type AgentCard ¶
type AgentCard struct {
ParentID string `json:"parentID,omitempty"`
URL string `json:"url,omitempty"`
Tasks []CardTask `json:"tasks,omitempty"`
SourceID string `json:"sourceID,omitempty"`
PlanID string `json:"planID,omitempty"`
Kind CardKind `json:"kind"`
Title string `json:"title"`
Summary string `json:"summary"`
Details []CardDetail `json:"details,omitempty"`
Actions []CardAction `json:"actions,omitempty"`
Fields []FormField `json:"fields,omitempty"`
Status string `json:"status"`
Revision int64 `json:"revision"`
ExpiresTS *time.Time `json:"expiresTS,omitempty"`
Progress *int `json:"progress,omitempty"`
Result string `json:"result,omitempty"`
AnswerID string `json:"answerID,omitempty"`
}
type Attachment ¶
type Attachment struct {
ID string `json:"id"`
Kind string `json:"kind"`
Mime string `json:"mime"`
Size int64 `json:"size"`
Name string `json:"name,omitempty"`
Width int `json:"width,omitempty"`
Height int `json:"height,omitempty"`
Thumb bool `json:"thumb,omitempty"`
URL string `json:"url,omitempty"`
ThumbnailURL string `json:"thumbnailUrl,omitempty"`
}
Attachment is an uploaded image or file embedded in a message.
type Bot ¶
type Bot struct {
ArgumentCommands bool // opt in before Run to route declared command input
StartupCommands []*Command // published before connecting; nil leaves commands unchanged
InputMode string // optional mode to publish after StartupCommands
ID string // bot ID, resolved from the access token subject on Run
ClientID string
ClientSecret string
Messages chan *Message // incoming messages that are not registered commands
Commands chan *Message // incoming messages matching a registered command value
Settings chan *SessionSettings // per-session settings after a change (dropped when nobody reads)
Reactions chan *Message // reaction snapshots; dropped when nobody reads
ReadReceipts chan *ReadReceipt // receipts for the bot's messages (dropped when nobody reads)
CollectionRequests chan *CollectionRequest // native list/add/remove operations; reply with RespondCollection
// NewSession is called when a user opens a new session with the bot.
// Set it before calling Run.
NewSession func(session *Session)
// contains filtered or unexported fields
}
Bot is a BotComm bot: an authenticated client connected to the /updates event stream. Configure the exported fields before calling Run (or use New).
func New ¶
New creates a bot and runs it: authorizes with the client credentials, connects to the /updates stream and starts listening. The bot stops when ctx is cancelled or Stop is called. Supply at most one optional Opts value.
func (*Bot) Broadcast ¶
Broadcast sends content to every session of the bot as a server-side job. Poll BroadcastStatus for progress.
func (*Bot) BroadcastKeyboard ¶
func (b *Bot) BroadcastKeyboard(ctx context.Context, content string, options []KeyboardOption) (*Broadcast, error)
BroadcastKeyboard is Broadcast with one-tap answer options on every copy.
func (*Bot) BroadcastStatus ¶
BroadcastStatus returns the progress of a broadcast job.
func (*Bot) BroadcastWithOptions ¶
func (b *Bot) BroadcastWithOptions(ctx context.Context, content string, options SendOptions) (*Broadcast, error)
BroadcastWithOptions includes an optional subject or keyboard on every copy.
func (*Bot) Edit ¶
func (b *Bot) Edit(ctx context.Context, sessionID, messageID, content string, options ...KeyboardOption) (*Message, error)
Edit replaces the content of a message the bot sent. A non-nil options slice also replaces the keyboard (409 once the user has answered the old one).
func (*Bot) EditWithOptions ¶
func (b *Bot) EditWithOptions(ctx context.Context, sessionID, messageID string, options EditOptions) (*Message, error)
EditWithOptions changes content, subject or keyboard without changing other fields.
func (*Bot) FeaturedBots ¶
func (b *Bot) FeaturedBots(ctx context.Context) ([]*FeaturedBot, error)
FeaturedBots returns the curated public bots in the operator's order.
func (*Bot) GetCardMessage ¶
func (*Bot) GetMessage ¶
func (*Bot) RecentMessages ¶
RecentMessages returns up to the last 10 messages in a session, newest first.
func (*Bot) RegisterCollections ¶
func (b *Bot) RegisterCollections(ctx context.Context, fields []CollectionField) error
func (*Bot) RegisterCommands ¶
RegisterCommands publishes the bot commands to the API and routes incoming messages whose content equals a command value to the Commands channel.
func (*Bot) RegisterSettings ¶
func (b *Bot) RegisterSettings(ctx context.Context, fields []SettingField) error
RegisterSettings publishes the per-session settings schema (up to 20 fields) the app renders for users. Every Session then carries Settings with defaults filled in, and changes arrive on the Settings channel.
func (*Bot) RespondCollection ¶
func (b *Bot) RespondCollection(ctx context.Context, req *CollectionRequest, result CollectionResult) error
func (*Bot) Run ¶
Run authorizes the bot, connects to the event stream and starts the listen loop. It returns an error if the initial grant or connect fails; after that the SDK keeps the token fresh and reconnects on its own. Supply at most one optional Opts value; a non-nil value replaces the bot's startup fields. Setup runs before connecting and stops at the first error without rolling back earlier server updates. Reconnects do not republish configuration.
func (*Bot) Send ¶
func (b *Bot) Send(ctx context.Context, sessionID, content string, silent ...bool) (*Message, error)
Send posts a message into a session and returns it as stored.
func (*Bot) SendKeyboard ¶
func (b *Bot) SendKeyboard(ctx context.Context, sessionID, content string, options []KeyboardOption) (*Message, error)
SendKeyboard posts a message with one-tap answer options. The user's tap arrives on the Messages channel as a message whose Content is the chosen option's Label, with ReplyTo set to the keyboard message's id and Value to the option's Value (a Value matching a registered command is routed to the Commands channel instead).
func (*Bot) SendMessage ¶
func (*Bot) SendWithOptions ¶
func (b *Bot) SendWithOptions(ctx context.Context, sessionID, content string, options SendOptions) (*Message, error)
SendWithOptions posts a message with an optional subject, keyboard or attachments.
func (*Bot) SetInputMode ¶
SetInputMode configures user input. Publish commands successfully first.
func (*Bot) SetMessageAcceptor ¶
SetMessageAcceptor installs durable acceptance before delivery and read acknowledgment. Configure it before Run. Failed acceptance is retried until shutdown.
func (*Bot) SetOnlineStatusVisible ¶
SetOnlineStatusVisible controls whether apps show the bot's connection status.
func (*Bot) SetSettings ¶
func (b *Bot) SetSettings(ctx context.Context, sessionID string, values map[string]string) (*SessionSettings, error)
SetSettings changes settings of a session on the user's behalf and returns the effective values.
func (*Bot) StartStream ¶
StartStream creates one live bubble. Update it with accumulated text snapshots.
func (*Bot) Typing ¶
Typing shows a typing indicator to the user for a few seconds; call it again every 3-4s while a long reply is being prepared.
func (*Bot) UpdateCard ¶
func (b *Bot) UpdateCard(ctx context.Context, sessionID, messageID string, change CardUpdate) (*CardMessage, error)
func (*Bot) UpdateMessage ¶
func (*Bot) UpdateStream ¶
func (b *Bot) UpdateStream(ctx context.Context, sessionID, messageID string, input StreamInput) (*Message, error)
UpdateStream uses increasing sequence numbers; retry an identical snapshot safely. Batch updates at 500ms intervals and finish with status completed or failed.
func (*Bot) UploadAttachment ¶
func (b *Bot) UploadAttachment(ctx context.Context, sessionID, name string, data []byte) (*Attachment, error)
UploadAttachment uploads bytes for a session. Include the returned ID in SendOptions.Attachments within ten minutes to attach it to a message.
type Broadcast ¶
type Broadcast struct {
ID string `json:"id"`
Content string `json:"content"`
Subject string `json:"subject,omitempty"`
Metadata json.RawMessage `json:"metadata,omitempty"`
Silent bool `json:"silent"`
Total int `json:"total"`
Sent int `json:"sent"`
Failed int `json:"failed"`
Done bool `json:"done"`
CreateTS time.Time `json:"createTS"`
DoneTS *time.Time `json:"doneTS,omitempty"`
}
Broadcast is a message fanned out to every session of the bot by the server.
type CardAction ¶
type CardAction = Action
type CardDetail ¶
type CardMessage ¶
type CardMessage struct{ Message }
CardMessage is the legacy wrapper; new integrations use Message directly.
type CardTask ¶
type CardTask struct {
ID string `json:"id"`
Title string `json:"title"`
Status CardTaskStatus `json:"status"`
URL string `json:"url,omitempty"`
}
type CardTaskStatus ¶
type CardTaskStatus string
const ( CardTaskStatusQueued CardTaskStatus = "queued" CardTaskStatusRunning CardTaskStatus = "running" CardTaskStatusWaiting CardTaskStatus = "waiting" CardTaskStatusCompleted CardTaskStatus = "completed" CardTaskStatusFailed CardTaskStatus = "failed" CardTaskStatusCancelled CardTaskStatus = "cancelled" )
type CardUpdate ¶
type CollectionField ¶
type CollectionField struct {
Key string `json:"key"`
Label string `json:"label"`
Description string `json:"description,omitempty"`
Placeholder string `json:"placeholder,omitempty"`
MaxItems int `json:"maxItems"`
}
CollectionField declares a session-scoped list in native chat settings.
type CollectionItem ¶
type CollectionRequest ¶
type CollectionRequest struct {
ID string `json:"id"`
SessionID string `json:"sessionID"`
Key string `json:"key"`
Action string `json:"action"`
Value string `json:"value,omitempty"`
ItemID string `json:"itemID,omitempty"`
Revision *int64 `json:"revision,omitempty"`
ExpiresTS time.Time `json:"expiresTS"`
}
CollectionRequest arrives outside chat history. For add/remove, atomically compare Revision with stored state, mutate, and increment the revision in the same write. Reject mismatches without changing state, including duplicate requests after a lost response. Never execute an expired request.
type CollectionResult ¶
type CollectionResult struct {
Items []CollectionItem `json:"items"`
Revision int64 `json:"revision"`
Error string `json:"error,omitempty"`
Changed bool `json:"changed,omitempty"`
}
type Command ¶
type Command struct {
Input *CommandInput `json:"input,omitempty"`
Name string `json:"name"`
Value string `json:"value"`
Description string `json:"description"`
}
Command describes a bot command shown to users.
type CommandInput ¶
type CommandInput struct {
Type string `json:"type"`
Label string `json:"label,omitempty"`
Placeholder string `json:"placeholder,omitempty"`
Required bool `json:"required"`
MaxLength int `json:"maxLength,omitempty"`
}
CommandInput describes a single text argument collected by the client.
type EditOptions ¶
type EditOptions struct {
Content *string `json:"content,omitempty"`
Subject *string `json:"subject,omitempty"`
Metadata json.RawMessage `json:"metadata,omitempty"`
Keyboard *Keyboard `json:"keyboard,omitempty"`
}
EditOptions changes only non-nil fields. An empty Subject clears it. Metadata is a JSON object (up to 4096 bytes); json.RawMessage("null") clears it.
type Envelope ¶
type Envelope struct {
Type string `json:"type"`
Data json.RawMessage `json:"data"`
}
Envelope is a single /updates event: a JSON message with a type ("message", "new_session", "read", "settings") and a type-specific payload.
type FeaturedBot ¶
type FeaturedBot struct {
ID string `json:"id"`
Handle string `json:"handle"`
Name string `json:"name"`
}
FeaturedBot is a public bot in the operator's curated list.
type Keyboard ¶
type Keyboard struct {
Options []KeyboardOption `json:"options"`
Selected *string `json:"selected,omitempty"`
}
Keyboard is a set of one-tap answer options attached to a message. The server stamps Selected once the user answers; clients render an answered keyboard unclickable.
type KeyboardOption ¶
KeyboardOption is one tappable choice offered by a keyboard: Label is shown to the user, Value is what the bot receives when it is chosen.
type LinkPreview ¶
type LinkPreview struct {
URL string `json:"url"`
SiteName string `json:"siteName"`
Title string `json:"title"`
Description string `json:"description,omitempty"`
Image *PreviewImage `json:"image,omitempty"`
}
LinkPreview is optional article metadata generated by the server.
type Message ¶
type Message struct {
Stream *MessageStream `json:"stream,omitempty"`
Reactions map[string]string `json:"reactions,omitempty"`
ReactionRevision int64 `json:"reactionRevision,omitempty"`
Card *AgentCard `json:"card,omitempty"`
Fields map[string]any `json:"fields,omitempty"`
Cancel bool `json:"cancel,omitempty"`
ID string `json:"id"`
SessionID string `json:"sessionID"`
AuthorID string `json:"authorID"`
Command string `json:"-"` // matched value when ArgumentCommands is enabled
Argument string `json:"-"` // trimmed input; Content remains unchanged
LinkPreview *LinkPreview `json:"linkPreview,omitempty"`
PreviewTS *time.Time `json:"previewTS,omitempty"`
Content string `json:"content"`
Subject string `json:"subject,omitempty"`
Metadata json.RawMessage `json:"metadata,omitempty"`
// Keyboard is present on bot messages sent with one-tap answer options.
Keyboard *Keyboard `json:"keyboard,omitempty"`
Attachments []Attachment `json:"attachments,omitempty"`
// ReplyTo and Value are set on a user's answer to a keyboard message:
// ReplyTo is the id of the keyboard message, Value the machine value of
// the chosen option (Content carries its human-readable label).
ReplyTo string `json:"replyTo,omitempty"`
Value string `json:"value,omitempty"`
Silent bool `json:"silent"`
Read bool `json:"read"`
Delivered bool `json:"delivered"`
AuthorTS time.Time `json:"authorTS"`
CreateTS time.Time `json:"createTS"`
EditTS *time.Time `json:"editTS,omitempty"`
}
Message is a single chat message, as returned by the API.
type MessageInput ¶
type MessageInput struct {
IdempotencyKey string `json:"-"`
Stream bool `json:"stream,omitempty"`
Content string `json:"content,omitempty"`
Subject string `json:"subject,omitempty"`
Metadata json.RawMessage `json:"metadata,omitempty"`
Actions []Action `json:"actions,omitempty"`
Card *AgentCard `json:"card,omitempty"`
Keyboard *Keyboard `json:"keyboard,omitempty"`
Attachments []string `json:"attachments,omitempty"`
Silent bool `json:"silent"`
TS time.Time `json:"ts"`
}
type MessageStream ¶
type MessageUpdate ¶
type MessageUpdate struct {
Content *string `json:"content,omitempty"`
Subject *string `json:"subject,omitempty"`
Metadata json.RawMessage `json:"metadata,omitempty"`
Actions []Action `json:"actions,omitempty"`
Card *CardUpdate `json:"card,omitempty"`
Keyboard *Keyboard `json:"keyboard,omitempty"`
}
type Opts ¶
type Opts struct {
Commands []*Command
Settings []SettingField
Collections []CollectionField
InputMode string
OnlineStatusVisible *bool
ArgumentCommands bool
NewSession func(session *Session)
}
Opts configures startup. Nil slices, an empty InputMode and nil OnlineStatusVisible leave the corresponding server configuration unchanged. Non-nil empty slices clear the corresponding definitions.
func (*Opts) SetArgumentCommands ¶
SetArgumentCommands enables or disables routing of declared command input.
func (*Opts) SetCollections ¶
func (o *Opts) SetCollections(fields []CollectionField) *Opts
SetCollections sets the session collection schema to publish before connecting.
func (*Opts) SetCommands ¶
SetCommands sets the command definitions to publish before connecting.
func (*Opts) SetInputMode ¶
SetInputMode sets the startup input mode: "messages", "commands" or "none".
func (*Opts) SetNewSession ¶
SetNewSession sets the callback invoked when a user opens a new session.
func (*Opts) SetOnlineStatusVisible ¶
SetOnlineStatusVisible sets whether apps show the bot's connection status.
func (*Opts) SetSettings ¶
func (o *Opts) SetSettings(fields []SettingField) *Opts
SetSettings sets the per-session settings schema to publish before connecting.
type PreviewImage ¶
type ReadReceipt ¶
type ReadReceipt struct {
SessionID string `json:"sessionID"`
MessageID string `json:"messageID"`
By string `json:"by,omitempty"`
}
ReadReceipt identifies a message read by the other side of a session.
type SendOptions ¶
type SendOptions struct {
Stream bool `json:"stream,omitempty"`
Subject string `json:"subject,omitempty"`
Metadata json.RawMessage `json:"metadata,omitempty"`
Keyboard *Keyboard `json:"keyboard,omitempty"`
Attachments []string `json:"attachments,omitempty"`
Silent bool `json:"silent"`
}
SendOptions configures an optional subject, keyboard, attachments and push suppression.
type Session ¶
type Session struct {
ID string `json:"id"`
User *User `json:"user,omitempty"`
UnreadCount int `json:"unreadCount"`
LastMessage *Message `json:"lastMessage,omitempty"`
Settings map[string]string `json:"settings,omitempty"` // effective values of the registered settings
Muted bool `json:"muted"` // the user receives no push for this session
CreateTS time.Time `json:"createTS"`
}
Session is a conversation between one account and the bot.
type SessionSettings ¶
type SessionSettings struct {
SessionID string `json:"sessionID"`
Settings map[string]string `json:"settings"`
}
SessionSettings are the effective settings of a session, defaults included.
type SettingField ¶
type SettingField struct {
Key string `json:"key"`
Label string `json:"label"`
Description string `json:"description,omitempty"`
Type string `json:"type"`
Options []KeyboardOption `json:"options,omitempty"`
Default string `json:"default,omitempty"`
}
SettingField is one entry of the bot's per-session settings schema, rendered by the app as a form control. Type is "toggle" ("true"/"false"), "select" (Options), "text" or "time" ("HH:MM"); values are always strings.