bot

package
v0.0.0-...-1791c78 Latest Latest
Warning

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

Go to latest
Published: Nov 25, 2026 License: MIT Imports: 40 Imported by: 1 module, 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 bot is the Super Chat bot SDK. A bot is a process with its own Super Chat account: it joins rooms through invite links, reads every message, and answers the ones that tag it ("@Emma roll 2d6").

b, err := bot.New(bot.Config{DataDir: "/var/lib/mybot"})
b.Command("roll", bot.Anyone, "roll dice: roll 2d6", func(c *bot.Ctx) error {
	return c.Reply("4")
})
err = b.Run(ctx)

The account is made once with Init (or the stock CLI's init). Everything the protocol asks of a room member is handled here: verifying the room's log, opening keys, rotating them when someone leaves, keeping the bot's profile readable for people who join later, and catching up on whatever was said while the bot was down.

Index

Constants

View Source
const AvatarSize = 512

AvatarSize is the side of a profile picture, as the app makes them.

View Source
const ControlSocket = "control.sock"

ControlSocket is the socket's file name in the data directory.

View Source
const MaxNameLen = 40

MaxNameLen is how long a display name can be: the app cuts names at 40 (UTF-16 units), so the bot's own names never go past that.

Variables

View Source
var (
	ErrReplaced  = errors.New("replaced by another Play")
	ErrCallEnded = errors.New("the call ended")
)

ErrReplaced and ErrCallEnded end a Playback early.

View Source
var DefaultICEServers = []webrtc.ICEServer{{URLs: []string{"stun:stun.l.google.com:19302"}}}

DefaultICEServers is the app's default: a public STUN server.

View Source
var DefaultNames = []string{
	"James", "Mary", "John", "Patricia", "Robert", "Jennifer", "Michael", "Linda",
	"William", "Elizabeth", "David", "Barbara", "Richard", "Susan", "Joseph", "Jessica",
	"Thomas", "Sarah", "Charles", "Karen", "Daniel", "Nancy", "Matthew", "Lisa",
	"Anthony", "Betty", "Mark", "Margaret", "Steven", "Sandra", "Paul", "Ashley",
	"Andrew", "Emily", "Joshua", "Donna", "Kevin", "Michelle", "Brian", "Carol",
	"George", "Amanda", "Edward", "Melissa", "Ryan", "Deborah", "Jacob", "Rebecca",
	"Gary", "Laura",
}

DefaultNames is where a new bot's name comes from when none is given.

View Source
var ErrNotAllowed = errors.New("the bot isn't allowed to do that here")

ErrNotAllowed means the bot may not do that in this room.

View Source
var ErrVoiceFull = errors.New("the voice room is full (8/8)")

ErrVoiceFull means the voice room already has 8 people.

Functions

func Mention

func Mention(memberID string) string

Mention is the token that tags a member in a message's text.

func PrepareAvatar

func PrepareAvatar(data []byte) ([]byte, error)

PrepareAvatar turns any JPEG, PNG, GIF or WebP into a profile picture the way the app does: the centered square, scaled to AvatarSize, as a JPEG.

func RandomName

func RandomName() string

RandomName picks one of DefaultNames.

func SetPassword

func SetPassword(dataDir, password string) error

SetPassword changes the admin password of the account in dataDir. Members already logged in stay logged in.

Types

type Access

type Access int

Access says who may run a command.

const (
	// Anyone in the room.
	Anyone Access = iota
	// Admin: only members who logged in with the bot's admin password (in
	// this room: member IDs are per room).
	Admin
)

type Account

type Account struct {
	Name string
	// Phrase is the recovery phrase: shown once, so it can be written down.
	// The same phrase also opens the bot's account in the app.
	Phrase []string
}

Account is what Init made.

func Init

func Init(dataDir string, opt InitOptions) (*Account, error)

Init creates a bot account in dataDir. It refuses to replace one.

type Bot

type Bot struct {

	// Voice is the bot's voice side: presence, and joining calls.
	Voice *Voice
	// contains filtered or unexported fields
}

Bot is one bot account.

func New

func New(cfg Config) (*Bot, error)

New opens the bot in cfg.DataDir.

func (*Bot) CheckPassword

func (b *Bot) CheckPassword(pw string) bool

CheckPassword reports whether pw is the bot's admin password.

func (*Bot) Close

func (b *Bot) Close() error

Close releases the data directory. Call it after Run returns.

func (*Bot) Command

func (b *Bot) Command(name string, who Access, usage string, fn func(*Ctx) error)

Command registers a command: the first word after the bot's mention. usage is shown by help. Registering a name again replaces it.

func (*Bot) Commands

func (b *Bot) Commands() []CommandInfo

Commands lists the registered commands, by name.

func (*Bot) Join

func (b *Bot) Join(ctx context.Context, link string) (Room, error)

Join joins a room through an invite link: the https form or the app's superchat:// form. Joining a room the bot is already in just returns it. The bot must be running.

func (*Bot) Leave

func (b *Bot) Leave(ctx context.Context, roomID string) error

Leave has the bot leave a room. The rest of the room re-keys without it.

func (*Bot) Name

func (b *Bot) Name() string

Name is the bot's display name.

func (*Bot) OnJoin

func (b *Bot) OnJoin(fn func(context.Context, Room))

OnJoin runs after the bot joins a room.

func (*Bot) OnMessage

func (b *Bot) OnMessage(fn func(*Ctx) error)

OnMessage runs fn for every message from someone else, tagged or not: text, files, edits and reactions alike (see Ctx.Message.Content.T).

func (*Bot) OnRemoved

func (b *Bot) OnRemoved(fn func(ctx context.Context, roomID string))

OnRemoved runs after the bot leaves a room or is removed from it, once it has forgotten the room. It's never rejoined on its own.

func (*Bot) OnStart

func (b *Bot) OnStart(fn func(ctx context.Context))

OnStart runs once Run has loaded the bot's rooms (and keeps running for as long as ctx lasts, so it can start long-lived work: say, joining voice).

func (*Bot) OnVoiceJoined

func (b *Bot) OnVoiceJoined(fn func(ctx context.Context, c *Call))

OnVoiceJoined runs when the bot has joined a room's voice.

func (*Bot) OnVoiceLeft

func (b *Bot) OnVoiceLeft(fn func(ctx context.Context, roomID, why string))

OnVoiceLeft runs when the bot's call ends: it left, it was removed from the room, or the bot is shutting down.

func (*Bot) OnVoicePeerJoined

func (b *Bot) OnVoicePeerJoined(fn func(ctx context.Context, c *Call, s VoiceSession))

OnVoicePeerJoined runs when someone's connection to the bot comes up.

func (*Bot) OnVoicePeerLeft

func (b *Bot) OnVoicePeerLeft(fn func(ctx context.Context, c *Call, s VoiceSession))

OnVoicePeerLeft runs when someone the bot was connected to leaves or drops.

func (*Bot) OnVoicePresence

func (b *Bot) OnVoicePresence(fn func(ctx context.Context, roomID string, before, after []VoiceSession))

OnVoicePresence runs when someone joins or leaves a room's voice, times out, or changes mute or sound off (whether or not the bot is in it).

func (*Bot) Picture

func (b *Bot) Picture() []byte

Picture is the bot's profile picture (a JPEG), or nil.

func (*Bot) Rooms

func (b *Bot) Rooms() []Room

Rooms is every room the bot is in.

func (*Bot) Run

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

Run connects to every room's server and handles messages until ctx ends.

func (*Bot) Send

func (b *Bot) Send(ctx context.Context, roomID, text string) error

Send posts a message in a room the bot is in, outside of any handler (say, "now playing" when a queued song starts).

func (*Bot) SetAdmin

func (b *Bot) SetAdmin(roomID, member string, admin bool) error

SetAdmin makes a member an admin of the bot in a room (or not). Member IDs are per room, so it's only ever for that room.

func (*Bot) SetName

func (b *Bot) SetName(ctx context.Context, name string) error

SetName renames the bot in every room. A room that can't be reached now catches up on its own the next time it syncs; the error names how many.

func (*Bot) SetPicture

func (b *Bot) SetPicture(ctx context.Context, image []byte) error

SetPicture sets the bot's profile picture in every room: any JPEG, PNG, GIF or WebP, cropped and scaled like the app's (PrepareAvatar). nil removes it.

func (*Bot) Unknown

func (b *Bot) Unknown(fn func(*Ctx) error)

Unknown handles a mention whose first word isn't a command. By default the bot says it doesn't know it and points at help.

type Call

type Call struct {
	// contains filtered or unexported fields
}

Call is the bot in a room's voice. It sends one audio track to everyone in the mesh and receives nothing.

func (*Call) Done

func (c *Call) Done() <-chan struct{}

Done is closed when the call has ended; Why says why.

func (*Call) Leave

func (c *Call) Leave(ctx context.Context) error

Leave leaves the call.

func (*Call) Muted

func (c *Call) Muted() bool

Muted reports whether the bot is muted.

func (*Call) Peers

func (c *Call) Peers() []VoiceSession

Peers is who the bot is connected to (or connecting to) in the call.

func (*Call) Play

func (c *Call) Play(src audio.Source) *Playback

Play plays a source to everyone in the call, replacing whatever was playing. Between sources the bot sends silence.

The source is read ahead on a goroutine of its own, into a buffer of about a second. A source that falls behind (a live stream stalling) never holds up what's sent: those frames go out as silence and listeners hear a gap, but packets keep flowing, so no app shows the bot as buffering. (A Next that blocks for ever can only be ended by its source: close the reader.)

func (*Call) RoomID

func (c *Call) RoomID() string

RoomID is the room this call is in.

func (*Call) SetMuted

func (c *Call) SetMuted(muted bool)

SetMuted mutes the bot (it sends silence, and the room shows it muted).

func (*Call) Why

func (c *Call) Why() string

Why is why the call ended ("left", "removed from the room", "the bot stopped", or "the voice room is full"), once Done is closed.

type CommandInfo

type CommandInfo struct {
	Name  string
	Who   Access
	Usage string
}

CommandInfo describes a registered command.

type Config

type Config struct {
	// DataDir holds the bot's account and state (made with Init).
	DataDir string
	// EntropyFile, if set, is where the account secret is read from instead
	// of DataDir (for secrets managers).
	EntropyFile string
	// Logger defaults to slog.Default().
	Logger *slog.Logger
	// Now is the clock; for tests.
	Now func() time.Time
	// SendBurst and SendsPerSecond limit what the bot posts in one room, so a
	// handler stuck in a loop can't flood a chat: a burst of SendBurst, then
	// SendsPerSecond. Sends past the limit wait. Defaults: 10, then 1 a second.
	SendBurst      int
	SendsPerSecond float64
	// ICEServers are the STUN/TURN servers for voice. nil means
	// DefaultICEServers (the app's default); an empty list means none, so
	// only direct connections work (fine on one network, or with a public IP).
	ICEServers []webrtc.ICEServer
}

Config sets up a Bot.

type Ctx

type Ctx struct {
	context.Context
	Bot     *Bot
	Room    Room
	Sender  Member
	Message *Message
	// Command and Args are set when the message tagged the bot: the first
	// word after the mention (lowercased), and the words after it.
	Command string
	Args    []string
	// contains filtered or unexported fields
}

Ctx is one message being handled.

func (*Ctx) Attachments

func (c *Ctx) Attachments() []crypto.FileRef

Attachments is the files on the message (none for plain text).

func (*Ctx) Delete

func (c *Ctx) Delete() error

Delete deletes the message for everyone. The room only lets the bot do that when it's a room admin; otherwise it's ErrNotAllowed.

func (*Ctx) Download

func (c *Ctx) Download(f crypto.FileRef) ([]byte, error)

Download fetches and opens one of the message's attachments.

func (*Ctx) Get

func (c *Ctx) Get(key string) ([]byte, error)

Get reads a value this bot stored for the room (nil if none).

func (*Ctx) IsAdmin

func (c *Ctx) IsAdmin() bool

IsAdmin reports whether the sender has logged in as an admin of the bot in this room.

func (*Ctx) Me

func (c *Ctx) Me() string

Me is the bot's own member ID in this room.

func (*Ctx) React

func (c *Ctx) React(emoji string) error

React puts an emoji on the message.

func (*Ctx) Reply

func (c *Ctx) Reply(text string) error

Reply answers the message, as a reply to it.

func (*Ctx) Send

func (c *Ctx) Send(text string) error

Send posts a message in the room.

func (*Ctx) SendFile

func (c *Ctx) SendFile(name, mime string, data []byte, caption string) error

SendFile posts a file in the room, with an optional caption. The app shows image/* as a picture, video/* and audio/* as players, anything else as a file to save.

func (*Ctx) Set

func (c *Ctx) Set(key string, value []byte) error

Set stores a value for the room; nil deletes it. It's forgotten with the room.

type InitOptions

type InitOptions struct {
	// Phrase restores an existing account from its 24-word recovery phrase;
	// empty makes a new one.
	Phrase string
	// Name is the display name; empty picks a random one from DefaultNames.
	Name string
	// Password is the admin password, given in chat to `login`. Required.
	Password string
}

InitOptions sets up a new bot account.

type Member

type Member struct {
	ID   string
	Name string // "" until their profile has been read
	Role string // the room role: "admin" or "member" (not the bot's admin)
}

Member is someone in a room. IDs are per room: the same person has a different ID in every room.

type Message

type Message struct {
	ID      string
	Pos     int64
	Ts      int64 // when the sender says they sent it (ms)
	Content crypto.Content
	// Raw is the whole decrypted content, for types Content doesn't cover.
	Raw []byte
}

Message is a message someone sent.

func (*Message) Mentions

func (m *Message) Mentions() []string

Mentions is the member IDs tagged in the message, in order.

func (*Message) Text

func (m *Message) Text() string

Text is the message's text: a text message's body or a file's caption.

type Playback

type Playback struct {
	// contains filtered or unexported fields
}

Playback is one source playing.

func (*Playback) Done

func (p *Playback) Done() <-chan struct{}

Done is closed once the source has played to its end, was stopped or replaced, or the call ended.

func (*Playback) Err

func (p *Playback) Err() error

Err is why it ended (after Done): nil when it played to the end or was stopped, ErrReplaced, ErrCallEnded, or the source's own error.

func (*Playback) Pause

func (p *Playback) Pause()

Pause holds the playback where it is; the bot sends silence meanwhile (the stream never stops, so nobody's app shows it buffering). Resume carries on from the same place.

func (*Playback) Paused

func (p *Playback) Paused() bool

Paused reports whether the playback is paused.

func (*Playback) Resume

func (p *Playback) Resume()

Resume carries on after Pause.

func (*Playback) Stop

func (p *Playback) Stop()

Stop stops it; the bot goes back to silence.

type Room

type Room struct {
	ID     string
	Server string
	// Name is the room's name, "" if it has none (the app then shows the
	// members' names).
	Name    string
	Members []Member
}

Room is a room as handlers see it.

func ControlJoin

func ControlJoin(dataDir, link string) (Room, error)

ControlJoin asks the bot running on dataDir to join a room.

func ControlRooms

func ControlRooms(dataDir string) ([]Room, error)

ControlRooms asks the bot running on dataDir which rooms it's in.

type Voice

type Voice struct {
	// contains filtered or unexported fields
}

Voice is the bot's voice side: b.Voice.

func (*Voice) Call

func (v *Voice) Call(roomID string) *Call

Call is the bot's call in a room, or nil when it isn't in its voice.

func (*Voice) Join

func (v *Voice) Join(ctx context.Context, roomID string) (*Call, error)

Join joins a room's voice. Joining one the bot is already in returns that call. A bot can be in the voice of many rooms at once (a phone can't).

func (*Voice) Presence

func (v *Voice) Presence(roomID string) []VoiceSession

Presence is who's in a room's voice, other than the bot. It works without joining: the bot asks when it connects, and everyone in voice says so every 15 s. Someone not heard from for 40 s has gone.

type VoiceSession

type VoiceSession struct {
	Member string
	Sid    string // per voice session: one person on two devices is two sessions
	Name   string
	Muted  bool
	Deaf   bool // sound off
}

VoiceSession is one person (one device) in a room's voice.

Directories

Path Synopsis
Package audio is what a bot plays into a voice room: a Source of Opus packets, from an Ogg Opus file (no codec library needed) or, built with -tags opus, from raw PCM (that needs libopus).
Package audio is what a bot plays into a voice room: a Source of Opus packets, from an Ogg Opus file (no codec library needed) or, built with -tags opus, from raw PCM (that needs libopus).
Package cli is the command line every bot gets: init, run, join, rooms and passwd.
Package cli is the command line every bot gets: init, run, join, rooms and passwd.
cmd
superchat-bot command
superchat-bot is the stock bot: the SDK with only the core commands.
superchat-bot is the stock bot: the SDK with only the core commands.
Package core holds the bot's built-in commands.
Package core holds the bot's built-in commands.
examples
radio command
radio is an example bot: the stock bot, plus music.
radio is an example bot: the stock bot, plus music.
internal
api
Package api talks to one Super Chat server: signed HTTP requests (there are no logins; each request is signed by the member key for its room) and the WebSocket that pushes events, messages and voice signaling.
Package api talks to one Super Chat server: signed HTTP requests (there are no logins; each request is signed by the member key for its room) and the WebSocket that pushes events, messages and voice signaling.
store
Package store is a bot's state on disk: one SQLite file (pure Go, no cgo) in the bot's data directory, plus the account secret in a file of its own.
Package store is a bot's state on disk: one SQLite file (pure Go, no cgo) in the bot's data directory, plus the account secret in a file of its own.

Jump to

Keyboard shortcuts

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