botwebhook

package
v0.3.103-beta Latest Latest
Warning

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

Go to latest
Published: Nov 27, 2026 License: AGPL-3.0 Imports: 33 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package botwebhook implements bots: named posters bound to one conversation, driven from outside through a Discord-compatible webhook URL whose token is the credential.

Index

Constants

View Source
const (
	TopicCreated  = "botwebhook.created"
	TopicUpdated  = "botwebhook.updated"
	TopicDeleted  = "botwebhook.deleted"
	TopicRestored = "botwebhook.restored"
)

Topics published by the botwebhook domain.

View Source
const (
	MaxBodyBytes = 64 << 10
)

Discord's execute-webhook limits, in characters after trimming, as Discord measures them.

View Source
const MaxLive = 10

MaxLive is how many live bots one conversation holds; a deleted bot frees its place.

View Source
const MaxNameLength = 80

MaxNameLength is the longest name a bot takes, in characters, as Discord's webhook names.

Variables

View Source
var ErrUnknownWebhook = fmt.Errorf("%w: unknown webhook", apperrs.ErrNotFound)

ErrUnknownWebhook answers every refused URL alike: a wrong id, a wrong or old token, a deleted bot.

Functions

func MCPTools

func MCPTools(s *Service) []mcptool.Tool

MCPTools returns the bot tools; none posts as a bot, a sender uses the bot's URL like any other client.

func Topics

func Topics() []eventbus.Topic

Topics returns every topic the botwebhook domain publishes.

Types

type AllowedMentions

type AllowedMentions struct {
	Parse []string `json:"parse"`
	// Users are Nexul user ids or logins.
	Users []string `json:"users"`
}

AllowedMentions is Discord's allowed_mentions; roles and everyone are ignored, as Nexul mentions only people.

type Bot

type Bot struct {
	ID             string `json:"id"`
	ConversationID string `json:"conversation_id"`
	Name           string `json:"name"`
	// Avatar is a base64 data: URI like a person's avatar override; empty shows the built-in bot glyph.
	Avatar     string     `json:"avatar,omitempty"`
	CreatedBy  string     `json:"created_by"`
	CreatedAt  time.Time  `json:"created_at"`
	UpdatedAt  time.Time  `json:"updated_at"`
	LastPostAt *time.Time `json:"last_post_at,omitempty"`
	PostCount  int        `json:"post_count"`
	DeletedAt  *time.Time `json:"deleted_at,omitempty"`
	DeletedBy  string     `json:"deleted_by,omitempty"`
	URL        string     `json:"url,omitempty"`
	// Stopped says why a live bot's posts are refused: its creator may not post where it posts (ADR 0150).
	Stopped string `json:"stopped,omitempty"`
	Token   string `json:"-"`
}

Bot is one conversation's poster; Token stays server-side and URL is filled only for a caller holding botwebhook:write.

type Change

type Change string

Change names one part of a bot botwebhook.updated reports as changed.

const (
	ChangeRenamed     Change = "renamed"
	ChangeAvatar      Change = "avatar"
	ChangeRegenerated Change = "regenerated"
)

type Changes

type Changes struct {
	Name       *string `json:"name,omitempty"`
	Avatar     *string `json:"avatar,omitempty"`
	Regenerate bool    `json:"regenerate,omitempty"`
	Deleted    *bool   `json:"deleted,omitempty"`
}

Changes is a PATCH on a bot: a nil field keeps its value, an empty Avatar clears it, Deleted false restores.

type Config

type Config struct {
	Repo          Repo
	Gate          Gate
	Conversations Conversations
	Instance      InstanceURL
	Poster        Poster
	People        People
	Messages      Messages
}

Config wires Service's seams; the adapters live in the composition root.

type Conversation

type Conversation struct {
	ID          string
	WorkspaceID string
	// MembersOnly marks a DM or private channel, whose bot events never reach integrations or automations.
	MembersOnly bool
}

Conversation is what bots need of the conversation they post into, read through chat's own read rule.

type Conversations

type Conversations interface {
	Conversation(ctx context.Context, id string) (*Conversation, error)
}

Conversations reads a conversation as the actor on ctx through chat's read rule: a DM's participants, a private channel's members, a ticket or doc thread's own gate.

type Embed

type Embed struct {
	Title       string `json:"title,omitempty"`
	Description string `json:"description,omitempty"`
	URL         string `json:"url,omitempty"`
	// Timestamp is kept as the sender wrote it: Uptime Kuma, among others, sends a time that is not RFC 3339.
	Timestamp string       `json:"timestamp,omitempty"`
	Footer    *EmbedFooter `json:"footer,omitempty"`
	Image     *EmbedImage  `json:"image,omitempty"`
	Thumbnail *EmbedImage  `json:"thumbnail,omitempty"`
	Author    *EmbedAuthor `json:"author,omitempty"`
	Fields    []EmbedField `json:"fields,omitempty"`
}

Embed is one embed as a message stores it.

type EmbedAuthor

type EmbedAuthor struct {
	Name    string `json:"name"`
	URL     string `json:"url,omitempty"`
	IconURL string `json:"icon_url,omitempty"`
}

EmbedAuthor is an embed's author line.

type EmbedField

type EmbedField struct {
	Name   string `json:"name"`
	Value  string `json:"value"`
	Inline bool   `json:"inline,omitempty"`
}

EmbedField is one name and value of an embed's fields.

type EmbedFooter

type EmbedFooter struct {
	Text    string `json:"text"`
	IconURL string `json:"icon_url,omitempty"`
}

EmbedFooter is an embed's footer line.

type EmbedImage

type EmbedImage struct {
	URL string `json:"url"`
}

EmbedImage is an embed's image or thumbnail.

type Event

type Event struct {
	BotwebhookID   string `json:"botwebhook_id"`
	ConversationID string `json:"conversation_id"`
	WorkspaceID    string `json:"workspace_id"`
	Name           string `json:"name" jsonschema:"The bot's name after the change."`
	ActorID        string `json:"actor_id,omitempty"`
	// Changes is set on botwebhook.updated only.
	Changes     []Change `` /* 132-byte string literal not displayed */
	MembersOnly bool     `` /* 148-byte string literal not displayed */
}

Event is every botwebhook.* payload; it never carries the token or the URL (ADR 0044: fields are additive-only).

type ExecuteHandler

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

ExecuteHandler serves the URL senders post to: no session, the token in the path is the credential, and it never passes the audit middleware, which records the raw path.

func NewExecuteHandler

func NewExecuteHandler(svc *Service, log *slog.Logger) *ExecuteHandler

NewExecuteHandler wires the public execute route over the given service.

func (*ExecuteHandler) Routes

func (h *ExecuteHandler) Routes() http.Handler

Routes returns the execute route, mounted before authentication.

type Gate

type Gate interface {
	Require(ctx context.Context, workspaceID string, action permissions.Action) error
}

Gate is the workspace permission check every use-case passes for its own botwebhook action.

type Handler

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

Handler adapts the bot use-cases to the HTTP/JSON gateway (ADR 0019); the public execute route is not here.

func NewHandler

func NewHandler(svc *Service) *Handler

NewHandler wires the bot management gateway over the given service; its media proxy dials public addresses only.

func (*Handler) Routes

func (h *Handler) Routes() http.Handler

Routes returns the bot management endpoints, mounted under /api/conversations and /api/botwebhooks.

type InstanceURL

type InstanceURL interface {
	GetInstanceURL(ctx context.Context) (string, error)
}

InstanceURL is the address senders reach this instance at, the base of every bot's URL.

type Message

type Message struct {
	ID        string        `json:"id"`
	ChannelID string        `json:"channel_id"`
	Content   string        `json:"content"`
	Embeds    []Embed       `json:"embeds"`
	Timestamp string        `json:"timestamp"`
	WebhookID string        `json:"webhook_id"`
	Author    MessageAuthor `json:"author"`
}

Message is the posted message as Discord answers wait=true.

type MessageAuthor

type MessageAuthor struct {
	ID       string `json:"id"`
	Username string `json:"username"`
	Avatar   string `json:"avatar"`
	Bot      bool   `json:"bot"`
}

MessageAuthor is the bot as a posted message names it.

type Messages

type Messages interface {
	BotMessage(ctx context.Context, id string) (*PostedMessage, error)
}

Messages reads one chat message with no gate of its own; the media proxy checks its conversation as the caller.

type Payload

type Payload struct {
	Content         string           `json:"content"`
	Username        string           `json:"username"`
	AvatarURL       string           `json:"avatar_url"`
	Embeds          []Embed          `json:"embeds"`
	AllowedMentions *AllowedMentions `json:"allowed_mentions"`
}

Payload is Discord's execute-webhook JSON; fields Discord takes and Nexul does not, color among them, are dropped.

type People

type People interface {
	Members(ctx context.Context, conversationID string) ([]Person, error)
}

People lists who a bot's post may mention: the members of its conversation's workspace.

type Person

type Person struct {
	ID, Login string
}

Person is a workspace member a bot's post may mention.

type Post

type Post struct {
	ConversationID, BotID, Name, AvatarURL, Body string
	// CreatorID is who made the bot, whose posting check the post takes (ADR 0150).
	CreatorID string
	Embeds    json.RawMessage
	// Mentionable are the logins the body's @handles may mention; any other handle stays plain text.
	Mentionable []string
	// Via is the bot's own name when the post overrode it, empty otherwise.
	Via string
	// Audit is the post's audit action: the route with its token stripped.
	Audit string
	// ID is the message's id when the poster derives one, so posting it again is ErrConflict; empty mints one.
	ID string
}

Post is one post through a bot's URL, as the bot's message stores it.

type PostedMessage

type PostedMessage struct {
	ConversationID string
	AvatarURL      string
	Embeds         json.RawMessage
	Deleted        bool
}

PostedMessage is what the media proxy needs of a stored message: where it lives and the images it may load.

type Poster

type Poster interface {
	// PostBotMessage writes the message, counts the post on its bot, and audits it, in one transaction; a post its
	// creator may not make there is ErrForbidden, saying so as Stopped does.
	PostBotMessage(ctx context.Context, p Post) (string, time.Time, error)
	// Stopped is "Stopped: <creator> can't post in #<channel>" while the bot's creator may not post where it posts,
	// else empty (ADR 0150).
	Stopped(ctx context.Context, conversationID, creatorID string) (string, error)
}

Poster posts a bot's message into its conversation; chat satisfies it, so chat never learns what a webhook is.

type Repo

type Repo interface {
	Create(ctx context.Context, b *Bot, evts ...eventbus.OutboxEvent) error
	// Get returns a bot deleted or not, with its token; ErrNotFound for none.
	Get(ctx context.Context, id string) (*Bot, error)
	// List returns a conversation's live bots, or its deleted ones, oldest first.
	List(ctx context.Context, conversationID string, deleted bool) ([]*Bot, error)
	// Update writes b's name, avatar, token, and deletion; ErrNotFound for a bot that is gone.
	Update(ctx context.Context, b *Bot, evts ...eventbus.OutboxEvent) error
}

Repo persists bots, their token sealed at rest; a duplicate live name in a conversation is ErrConflict.

type Service

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

Service is the botwebhook use-case layer; every mutation enqueues its event through the transactional outbox.

func NewService

func NewService(cfg Config) *Service

NewService wires the bot use-cases over the given seams.

func (*Service) Authenticate

func (s *Service) Authenticate(ctx context.Context, id, token string) (*Bot, error)

Authenticate returns the live bot a URL's id and token name, comparing the token in constant time; anything else is ErrUnknownWebhook, so no answer tells a wrong token from a missing bot.

func (*Service) Avatar

func (s *Service) Avatar(ctx context.Context, id string) (contentType string, data []byte, err error)

Avatar returns a bot's own avatar to anyone who reads its conversation: every reader sees its messages, so no botwebhook permission is asked.

func (*Service) Create

func (s *Service) Create(ctx context.Context, conversationID, name, avatar string) (*Bot, error)

Create adds a bot to a conversation with a fresh token, under botwebhook:write and the conversation's own gate.

func (*Service) Delete

func (s *Service) Delete(ctx context.Context, id string) (*Bot, error)

Delete soft-deletes a bot under botwebhook:delete: its URL dies at once and its name is freed; deleting it again is a no-op.

func (*Service) Execute

func (s *Service) Execute(ctx context.Context, b *Bot, p Payload) (*Message, error)

Execute posts p into b's conversation as b, the post's username and avatar_url overriding the bot's own; a bot deleted since Authenticate is ErrUnknownWebhook.

func (*Service) List

func (s *Service) List(ctx context.Context, conversationID string, deleted bool) ([]*Bot, error)

List returns a conversation's live bots, URLs only for botwebhook:write; the deleted list is for editors alone.

func (*Service) MediaURL

func (s *Service) MediaURL(ctx context.Context, messageID, raw string) (*url.URL, error)

MediaURL returns raw for the proxy to fetch only when the caller reads messageID's conversation and the message shows raw as one of its images, so the proxy never fetches a URL a reader did not already see.

func (*Service) Notify

func (s *Service) Notify(ctx context.Context, botID, id, content string) error

Notify posts content into a live bot's conversation as the bot, for the server's own notices, which reach no URL; a derived id makes posting it again change nothing. A deleted bot is ErrUnknownWebhook.

func (*Service) Update

func (s *Service) Update(ctx context.Context, id string, ch Changes) (*Bot, error)

Update renames, re-avatars, regenerates, restores, or deletes a bot; a restore issues a fresh token like a create.

Jump to

Keyboard shortcuts

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