botcomm

package module
v0.20261125.2 Latest Latest
Warning

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

Go to latest
Published: Nov 25, 2026 License: MIT Imports: 16 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.

README

BotComm Go SDK

Build bots with github.com/botcomm/go-client (package botcomm). See the echo example for credentials, lifecycle, and message handling.

ReadReceipts receives ReadReceipt events (SessionID, MessageID, By) when a user reads a bot message. Consume this buffered channel to react to reads; receipts are dropped when the buffer is full and are not replayed after reconnecting. FeaturedBots(ctx) returns the operator's ordered list of public bots.

Quickstart

Create a bot in the BotComm console and save its credentials. In the same terminal where you'll run the bot, set:

export CLIENT_ID='your-client-id'
export CLIENT_SECRET='your-client-secret'

In an empty directory, initialize a module and add the SDK (Go 1.23 or later):

go mod init example.com/echo
go get github.com/botcomm/go-client

Save this as main.go:

package main

import (
	"context"
	"log"
	"os"

	"github.com/botcomm/go-client"
)

func main() {
	ctx := context.Background()
	bot, err := botcomm.New(ctx, os.Getenv("CLIENT_ID"), os.Getenv("CLIENT_SECRET"), &botcomm.Opts{InputMode: "messages"})
	if err != nil {
		log.Fatal(err)
	}
	defer bot.Stop()

	for msg := range bot.Messages {
		if _, err := bot.Send(ctx, msg.SessionID, msg.Content); err != nil {
			log.Print(err)
		}
	}
}

Run go run ., open your bot’s chat in BotComm, and send hello. The bot should reply with hello.

Source layout

The SDK uses one botcomm package. Each feature keeps its types and methods together:

  • bot.go and options.go: bot lifecycle and startup configuration.
  • message.go, card.go and broadcast.go: messages, keyboards, streams, reactions, cards and broadcasts.
  • command.go and session.go: command registration and routing, sessions, settings and receipts.
  • attachment.go, collection.go and featured.go: attachments, session collections and featured bots.
  • auth.go and http.go: authentication, token renewal and HTTP requests.
  • updates.go and recovery.go: event streaming, reconnects and unread recovery.

Tests live alongside their features in *_test.go files.

Startup options

Pass an optional *botcomm.Opts to New. Setters update the same options value and return its pointer for chaining:

opts := &botcomm.Opts{}
opts.SetInputMode("commands").SetOnlineStatusVisible(true)
opts.SetCommands([]*botcomm.Command{
    {Name: "Help", Value: "/help", Description: "Show available commands"},
})

b, err := botcomm.New(ctx, clientID, clientSecret, opts)
if err != nil {
    return err
}
defer b.Stop()

Options also expose fields for struct literals, such as &botcomm.Opts{InputMode: "messages"}. Additional setters are SetSettings, SetCollections, SetArgumentCommands and SetNewSession. Configure the callback before startup so it can receive the first session event.

Nil slices, an empty input mode and nil OnlineStatusVisible preserve stored configuration. Non-nil empty slices clear commands, settings or collections. SetOnlineStatusVisible(false) explicitly hides the indicator; ArgumentCommands defaults to false.

Startup authenticates, publishes commands, settings and collections, applies visibility and input mode, then connects and recovers unread messages. A setup error stops startup and is returned to the caller; earlier server updates remain applied. Reconnects do not republish configuration.

Existing calls without options still work. Manual construction also supports b.Run(ctx, opts): a non-nil options value replaces the existing StartupCommands, InputMode, ArgumentCommands and NewSession fields for that startup. Omitted or nil options keep those fields. Both New and Run accept at most one options value.

Commands-only input

Configure before Run so unread recovery uses the same routing as live messages:

b := &botcomm.Bot{
    ClientID: clientID, ClientSecret: clientSecret,
    ArgumentCommands: true,
    InputMode: "commands",
    StartupCommands: []*botcomm.Command{
        {Name: "Set city", Value: "/city", Input: &botcomm.CommandInput{
            Type: "text", Label: "City", Placeholder: "Warsaw", Required: true,
        }},
    },
}
if err := b.Run(ctx); err != nil { return err }
// Read b.Commands: msg.Command == "/city", msg.Argument == "New York".
// msg.Content is still "/city New York".

SetInputMode(ctx, "messages") enables ordinary messages. RegisterCommands can update definitions at runtime.

Online status visibility

After Run, use SetOnlineStatusVisible(ctx, true) to show the bot's online/offline indicator in the web and iOS apps, or false to hide it. Check the returned error. The setting defaults to hidden and persists between restarts.

Receive-only mode and collections

Use input mode none for a receive-only chat. The composer is hidden. Users can still answer buttons, respond to cards, react to messages, and change session settings. Publish native session collections with RegisterCollections, CollectionRequests, and RespondCollection. Register the schema before enabling none. Persist and atomically compare/increment list revisions on mutations, reject expired requests, and return results outside chat history.

Photos and albums

Upload each image with UploadAttachment(ctx, sessionID, name, data), then pass the returned IDs in SendOptions.Attachments to SendWithOptions. Up to ten attachments share one message and its caption; content may be empty. Uploads belong to one session and must be attached within ten minutes. Images are limited to 5 MB each. Messages decode attachment metadata in Message.Attachments.

Message metadata

Message, MessageInput, MessageUpdate, SendOptions, EditOptions, and Broadcast expose Metadata as json.RawMessage. Supply a JSON object up to 4096 compact UTF-8 bytes. For edits, nil preserves it and json.RawMessage("null") removes it.

UpdateCard also accepts CardUpdate.Metadata and sends it as message metadata alongside the card update, with the same preserve, replace, and remove behavior.

Streaming replies and reactions

StartStream(ctx, sessionID) creates an empty live bubble. Call UpdateStream(ctx, sessionID, messageID, StreamInput{Content: text, Sequence: n, Status: "active"}) with accumulated text and increasing sequence numbers, batching at about 500ms. Finish with "completed" or "failed". Identical snapshot retries are safe; idle streams expire after two minutes, so send unchanged heartbeats while waiting for a provider. SendWithOptions also accepts SendOptions{Stream: true}.

React(ctx, sessionID, messageID, "❤️") replaces the bot's reaction; "" removes it. Read full message snapshots from bot.Reactions for live reaction changes. The queue is bounded; fetch the message after reconnect to reconcile old reactions. Reactions are separate from Messages and Commands.

Agent cards

Use SendMessage with MessageInput.Card and UpdateMessage with MessageUpdate.Card. Go uses AgentCard and CardUpdate; JSON fields parentID, sourceID, planID and url map to ParentID, SourceID, PlanID and URL.

Set MessageInput.IdempotencyKey to a stable value such as "themis:issue:" + issueNodeID when sending the first card. Retrying with the same key in that session returns the saved message. Use RecentMessages(ctx, sessionID) to read up to 10 messages from the conversation, newest first.

Set AgentCard.Kind using CardKindPlan, CardKindApproval, CardKindForm or CardKindArtifact. Convert existing string variables with CardKind(value).

Tasks use CardTask.Status with the CardTaskStatus type and constants CardTaskStatusQueued, CardTaskStatusRunning, CardTaskStatusWaiting, CardTaskStatusCompleted, CardTaskStatusFailed and CardTaskStatusCancelled. For example: CardTask{ID: "review", Title: "Review changes", Status: CardTaskStatusQueued}. Message and card send/update methods reject empty or unknown task statuses before making a request. Convert existing string variables with CardTaskStatus(value); string literals remain supported.

Kind Initial status Other statuses
plan queued running, waiting, completed, failed, cancelled
approval pending approved, rejected, expired, cancelled
form pending submitted, expired, cancelled
artifact completed None; immutable

The server sets the initial status and revision. Plan updates require the latest revision and a status other than queued; completed, failed and cancelled plans cannot be reopened. Stale revisions return 409. Approval/form updates only cancel pending, unexpired requests; answers and expiration determine their other statuses. Artifact cards cannot be updated.

An artifact requires an HTTP(S) url without credentials and may include parentID, the message ID of an existing plan from the same bot in the same chat.

sourceID is different: only plans accept it, pointing to an approved approval or submitted form from the same bot and chat. Each source permits one plan. The server sets planID on that source; never supply planID yourself. Links cannot be edited, and linking cards does not execute work.

A plan can contain up to 50 tasks. Updating its task list replaces the full list.

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

Constants

This section is empty.

Variables

This section is empty.

Functions

func SplitCommand

func SplitCommand(content string) (string, string)

SplitCommand preserves the argument as one text value, including internal spaces.

Types

type Action

type Action struct {
	Label string `json:"label"`
	Value string `json:"value"`
	Role  string `json:"role,omitempty"`
}

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

func New(ctx context.Context, clientID, clientSecret string, opts ...*Opts) (*Bot, error)

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

func (b *Bot) Broadcast(ctx context.Context, content string, silent ...bool) (*Broadcast, error)

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

func (b *Bot) BroadcastStatus(ctx context.Context, id string) (*Broadcast, error)

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

func (b *Bot) Delete(ctx context.Context, sessionID, messageID string) error

Delete removes a message the bot sent.

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 (b *Bot) GetCardMessage(ctx context.Context, sessionID, messageID string) (*CardMessage, error)

func (*Bot) GetMessage

func (b *Bot) GetMessage(ctx context.Context, sessionID, messageID string) (*Message, error)

func (*Bot) React

func (b *Bot) React(ctx context.Context, sessionID, messageID, emoji string) (*Message, error)

React replaces the bot's reaction; an empty emoji removes it.

func (*Bot) RecentMessages

func (b *Bot) RecentMessages(ctx context.Context, sessionID string) ([]*Message, error)

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

func (b *Bot) RegisterCommands(ctx context.Context, commands []*Command) error

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

func (b *Bot) Run(ctx context.Context, opts ...*Opts) error

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

func (b *Bot) SendCard(ctx context.Context, sessionID string, card AgentCard) (*CardMessage, error)

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 (b *Bot) SendMessage(ctx context.Context, sessionID string, input MessageInput) (*Message, error)

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

func (b *Bot) Sessions(ctx context.Context) ([]*Session, error)

Sessions fetches all sessions of the bot.

func (*Bot) SetInputMode

func (b *Bot) SetInputMode(ctx context.Context, mode string) error

SetInputMode configures user input. Publish commands successfully first.

func (*Bot) SetMessageAcceptor

func (b *Bot) SetMessageAcceptor(accept func(context.Context, *Message) error)

SetMessageAcceptor installs durable acceptance before delivery and read acknowledgment. Configure it before Run. Failed acceptance is retried until shutdown.

func (*Bot) SetOnlineStatusVisible

func (b *Bot) SetOnlineStatusVisible(ctx context.Context, visible bool) error

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

func (b *Bot) StartStream(ctx context.Context, sessionID string) (*Message, error)

StartStream creates one live bubble. Update it with accumulated text snapshots.

func (*Bot) Stop

func (b *Bot) Stop()

Stop cancels recovery, re-granting, and the event stream.

func (*Bot) Typing

func (b *Bot) Typing(ctx context.Context, sessionID string) error

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 (b *Bot) UpdateMessage(ctx context.Context, sessionID, messageID string, change MessageUpdate) (*Message, error)

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 CardDetail struct {
	Label string `json:"label"`
	Value string `json:"value"`
}

type CardKind

type CardKind string
const (
	CardKindPlan     CardKind = "plan"
	CardKindApproval CardKind = "approval"
	CardKindForm     CardKind = "form"
	CardKindArtifact CardKind = "artifact"
)

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 CardUpdate struct {
	Metadata json.RawMessage `json:"-"`
	Tasks    *[]CardTask     `json:"tasks,omitempty"`
	Revision int64           `json:"revision"`
	Status   string          `json:"status"`
	Progress *int            `json:"progress,omitempty"`
	Result   *string         `json:"result,omitempty"`
}

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 CollectionItem struct {
	ID          string `json:"id"`
	Label       string `json:"label"`
	Description string `json:"description,omitempty"`
}

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 FormField

type FormField struct {
	Key         string           `json:"key"`
	Label       string           `json:"label"`
	Type        string           `json:"type"`
	Required    bool             `json:"required,omitempty"`
	Placeholder string           `json:"placeholder,omitempty"`
	MaxLength   int              `json:"maxLength,omitempty"`
	Options     []KeyboardOption `json:"options,omitempty"`
}

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

type KeyboardOption struct {
	Label string `json:"label"`
	Value string `json:"value"`
}

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 MessageStream struct {
	Status    string    `json:"status"`
	Sequence  int64     `json:"sequence"`
	UpdatedTS time.Time `json:"updatedTS"`
}

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

func (o *Opts) SetArgumentCommands(enabled bool) *Opts

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

func (o *Opts) SetCommands(commands []*Command) *Opts

SetCommands sets the command definitions to publish before connecting.

func (*Opts) SetInputMode

func (o *Opts) SetInputMode(mode string) *Opts

SetInputMode sets the startup input mode: "messages", "commands" or "none".

func (*Opts) SetNewSession

func (o *Opts) SetNewSession(callback func(session *Session)) *Opts

SetNewSession sets the callback invoked when a user opens a new session.

func (*Opts) SetOnlineStatusVisible

func (o *Opts) SetOnlineStatusVisible(visible bool) *Opts

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 PreviewImage struct {
	ID     string `json:"id"`
	Width  int    `json:"width"`
	Height int    `json:"height"`
}

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.

type StreamInput

type StreamInput struct {
	Content  string `json:"content"`
	Sequence int64  `json:"sequence"`
	Status   string `json:"status"`
}

type User

type User struct {
	ID       string  `json:"id"`
	Name     *string `json:"name,omitempty"`
	Timezone *string `json:"timezone,omitempty"` // IANA zone, e.g. Europe/Kyiv
	Locale   *string `json:"locale,omitempty"`   // BCP 47 tag, e.g. uk-UA
}

User is the account on the other side of a session.

Jump to

Keyboard shortcuts

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