sdk

package
v1.2.0 Latest Latest
Warning

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

Go to latest
Published: Jun 11, 2026 License: MIT Imports: 17 Imported by: 0

Documentation

Overview

sdk 包提供 AnyBot 插件开发 SDK。

普通插件作者应优先使用本包,而不是直接依赖 core。插件通常导出一个 Plugin 定义,由运行框架在本地机器人目录中安装;Manifest.Name 只用于展示, PluginID 由宿主生成并作为配置、状态和私有数据目录的唯一身份。

最小插件形态:

var Plugin = sdk.Define(sdk.Spec[Config]{
	Manifest:      sdk.Manifest{Name: "hello", Version: "1.0.0"},
	DefaultConfig: Config{Command: "hello"},
	Setup: func(ctx *sdk.Context, cfg Config) error {
		ctx.Command(cfg.Command).Handle(func(c *sdk.EventContext) error {
			_, err := c.ReplyText("hello")
			return err
		})
		return nil
	},
})

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrActionUnavailable 表示动作客户端当前暂不可用。
	ErrActionUnavailable = core.ErrActionUnavailable
	// ErrReplyTargetUnavailable 表示当前事件或目标无法映射到可回复的会话。
	ErrReplyTargetUnavailable = core.ErrReplyTargetUnavailable
	// ErrSessionUnavailable 表示当前事件或运行时无法映射到请求的会话维度。
	ErrSessionUnavailable = core.ErrSessionUnavailable
	// ErrPass 表示当前路由主动让出处理权。
	ErrPass = core.ErrPass
	// ErrStop 表示当前事件应停止向后续路由传播。
	ErrStop = core.ErrStop
	// ErrUnauthorized 表示当前事件没有通过权限检查。
	ErrUnauthorized = core.ErrUnauthorized
	// ErrRateLimited 表示当前限速窗口已被耗尽。
	ErrRateLimited = core.ErrRateLimited
)
View Source
var ErrConfigStoreUnavailable = errors.New("anybot: plugin config store unavailable")

ErrConfigStoreUnavailable 表示当前运行时没有配置可写的插件配置存储。

View Source
var ErrDataDirUnavailable = errors.New("anybot: plugin data dir unavailable")

ErrDataDirUnavailable 表示当前运行时没有配置插件数据目录。

View Source
var ErrEventContextUnavailable = errors.New("anybot: event context unavailable")

ErrEventContextUnavailable 表示当前缺少事件上下文。

View Source
var ErrGlobalMiddlewareUnavailable = errors.New("anybot: global middleware is not available to this plugin")

ErrGlobalMiddlewareUnavailable 表示宿主没有授予插件注册全局中间件的能力。

View Source
var ErrGroupContextUnavailable = errors.New("anybot: group context unavailable")

ErrGroupContextUnavailable 表示当前事件没有群或频道上下文。

View Source
var ErrStateKeyRequired = errors.New("anybot: plugin state key is required")

ErrStateKeyRequired 表示 typed 状态缺少字段名。

View Source
var ErrStoreUnavailable = errors.New("anybot: plugin store unavailable")

ErrStoreUnavailable 表示当前运行时没有可用会话存储。

Functions

func Install

func Install(app *App, plugins ...Plugin) error

Install 将 SDK 插件安装到运行时。普通插件代码不需要接触 core.App 的内部安装细节。

func InstallCoreWith

func InstallCoreWith(app *core.App, env Environment, plugin Plugin) error

InstallCoreWith 将 SDK 插件安装到底层 core.App,供运行框架装配插件时使用。 普通插件作者应使用 anybot 运行框架、testkit,或 Install/InstallDefaultWith。

func InstallDefault

func InstallDefault(app *App, definitions ...Definition) error

InstallDefault 使用插件定义的默认配置安装插件,主要供插件测试和嵌入式程序使用。 它不会注入 PluginID、配置写回或插件数据目录;需要这些宿主能力时使用 InstallDefaultWith 或交给 anybot 运行框架安装。

func InstallDefaultWith

func InstallDefaultWith(app *App, env Environment, definition Definition) error

InstallDefaultWith 使用默认配置和显式宿主能力安装插件定义。

func InstallDefaultWithID

func InstallDefaultWithID(app *App, id string, definition Definition) error

InstallDefaultWithID 使用默认配置和显式稳定 PluginID 安装插件定义。 适合嵌入式机器人直接安装多个插件时隔离状态、任务和路由名称。

func InstallWith

func InstallWith(app *App, env Environment, plugin Plugin) error

InstallWith 使用显式宿主能力安装 SDK 插件。

func InstallWithID

func InstallWithID(app *App, id string, plugin Plugin) error

InstallWithID 使用显式稳定 PluginID 安装已构建好的插件对象。

func ParseConfigPath

func ParseConfigPath(input string) ([]string, error)

ParseConfigPath 解析插件 config 下的点分字段路径。

func ValidatePluginID

func ValidatePluginID(id string) error

ValidatePluginID 校验 PluginID 是否符合 AnyBot 生成的随机安装 ID 形态。

Types

type ActionClient

type ActionClient = core.ActionClient

ActionClient 是协议无关的消息发送接口。

type Adapter

type Adapter = core.Adapter

Adapter 把具体聊天协议接入 AnyBot 运行时。

type AdapterState

type AdapterState = core.AdapterState

AdapterState 描述动作通道状态。

type AdapterStateHook

type AdapterStateHook = core.AdapterStateHook

AdapterStateHook 观察动作通道状态变化。

type App

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

App 是 SDK 暴露的运行时句柄,常用于插件测试和嵌入式程序。

func NewApp

func NewApp(opts ...Option) *App

NewApp 创建测试或嵌入式运行时。常规插件安装逻辑应使用 Context 上的窄接口。

func (*App) Command

func (a *App) Command(names ...string) *Route

Command 注册命令路由。

func (*App) Dispatch

func (a *App) Dispatch(ctx context.Context, event *Event) error

Dispatch 将标准化事件直接投递给运行时。

func (*App) OnError

func (a *App) OnError(handler ErrorHandler)

OnError 注册错误处理器。

func (*App) OnMessage

func (a *App) OnMessage(rules ...Rule) *Route

OnMessage 注册消息事件路由。

func (*App) Runtime

func (a *App) Runtime() *core.App

Runtime 返回底层 core.App,供高级测试、嵌入式程序或框架适配代码使用。 普通插件不应依赖 core.App;优先使用 SDK 暴露的窄接口。

func (*App) Use

func (a *App) Use(middleware ...Middleware)

Use 注册全局中间件。

type ConfigAssignment

type ConfigAssignment struct {
	Path  []string
	Value any
}

ConfigAssignment 描述一次当前插件 config 下的字段写入。

type ConfigHandle

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

ConfigHandle 是当前插件配置写回入口。

func (ConfigHandle) Available

func (h ConfigHandle) Available() bool

Available 判断当前框架是否支持运行期写回插件配置。

func (ConfigHandle) Reset

func (h ConfigHandle) Reset(ctx context.Context, keys ...string) error

Reset 删除当前插件 config 下的字段覆盖。

func (ConfigHandle) Set

func (h ConfigHandle) Set(ctx context.Context, key string, value any) error

Set 写入当前插件 config 下的单个字段。

func (ConfigHandle) SetAll

func (h ConfigHandle) SetAll(ctx context.Context, assignments ...ConfigAssignment) error

SetAll 批量写入当前插件 config 下的字段。

type ConfigStore

type ConfigStore interface {
	SetPluginConfig(context.Context, string, []ConfigAssignment) error
	ResetPluginConfig(context.Context, string, [][]string) error
}

ConfigStore 是运行框架注入的插件配置写回能力。方法的 plugin 参数是当前 插件的 PluginID,不是 Manifest.Name。

type Context

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

Context 是成熟插件的安装上下文,暴露插件应使用的运行时能力。

func NewContext

func NewContext(app *App, manifest Manifest, opts ...InstallOption) *Context

NewContext 创建插件安装上下文,主要供运行框架或测试使用。

func (*Context) Client

func (c *Context) Client() ActionClient

Client 返回当前动作客户端。

func (*Context) Command

func (c *Context) Command(names ...string) *Route

Command 注册命令路由。

func (*Context) Config

func (c *Context) Config() ConfigHandle

Config 返回当前插件的配置写回入口。

func (*Context) DataDir

func (c *Context) DataDir() (string, error)

DataDir 返回当前插件 ID 的私有数据目录,并确保目录已创建。

func (*Context) Dialogue

func (c *Context) Dialogue(name string, opts ...DialogueOption) *Dialogue

Dialogue 创建插件命名空间内的多轮对话控制器,并注册用于恢复对话的高优先级消息路由。

func (*Context) Every

func (c *Context) Every(name string, interval time.Duration, fn TaskFunc, opts ...TaskOption)

Every 注册生命周期托管的周期任务。

func (*Context) Go

func (c *Context) Go(name string, fn TaskFunc, opts ...TaskOption)

Go 注册生命周期托管的后台任务。

func (*Context) GoWhenActionReady

func (c *Context) GoWhenActionReady(name string, fn TaskFunc, opts ...TaskOption)

GoWhenActionReady 注册等待动作客户端可用后执行的生命周期托管后台任务。

func (*Context) GroupSession

func (c *Context) GroupSession(event *EventContext) *Session

GroupSession 返回当前 PluginID 命名空间下的群或频道存储视图。

func (*Context) Logger

func (c *Context) Logger() *slog.Logger

Logger 返回框架日志器。

func (*Context) Manifest

func (c *Context) Manifest() Manifest

Manifest 返回当前插件清单。

func (*Context) Observe

func (c *Context) Observe(rules ...Rule) *Observer

Observe 注册事件旁路观察者。

func (*Context) On

func (c *Context) On(rules ...Rule) *Route

On 注册通用事件路由。

func (*Context) OnAdapterState

func (c *Context) OnAdapterState(hook AdapterStateHook)

OnAdapterState 注册动作通道状态钩子。

func (*Context) OnMessage

func (c *Context) OnMessage(rules ...Rule) *Route

OnMessage 注册消息事件路由。

func (*Context) OnReady

func (c *Context) OnReady(hook Hook)

OnReady 注册就绪钩子,事件调度器准备好后、适配器启动前执行。

func (*Context) OnShutdown

func (c *Context) OnShutdown(hook Hook)

OnShutdown 注册关闭钩子。

func (*Context) OnStart

func (c *Context) OnStart(hook Hook)

OnStart 注册启动钩子,适配器启动前执行。

func (*Context) PluginID

func (c *Context) PluginID() string

PluginID 返回当前插件在本地机器人目录中的稳定安装 ID。

func (*Context) Send

func (c *Context) Send(ctx context.Context, target ReplyTarget, chain message.Chain) (MessageReceipt, error)

Send 使用当前动作客户端发送消息。

func (*Context) SendText

func (c *Context) SendText(ctx context.Context, target ReplyTarget, text string) (MessageReceipt, error)

SendText 使用当前动作客户端发送纯文本消息。

func (*Context) Session

func (c *Context) Session(event *EventContext) *Session

Session 返回当前 PluginID 命名空间下的会话存储视图。

func (*Context) SessionBy

func (c *Context) SessionBy(key string) *Session

SessionBy 返回当前 PluginID 命名空间下的自定义存储视图。

func (*Context) Store

func (c *Context) Store() Store

Store 返回框架会话存储。

func (*Context) Use

func (c *Context) Use(middleware ...Middleware)

Use 注册插件级中间件,只作用于当前插件通过 Context 注册的后续路由。

func (*Context) UseGlobal

func (c *Context) UseGlobal(middleware ...Middleware) error

UseGlobal 注册框架级全局中间件。只有运行框架显式授权的内置策略插件才应使用。

func (*Context) UserSession

func (c *Context) UserSession(event *EventContext) *Session

UserSession 返回当前 PluginID 命名空间下的用户存储视图。

func (*Context) WaitActionReady

func (c *Context) WaitActionReady(ctx context.Context) error

WaitActionReady 等待动作客户端可用。

type Definition

type Definition interface {
	Manifest() Manifest
	Build() (Plugin, error)
	Factory() Factory
}

Definition 是插件定义,可转成运行框架工厂,也可用默认配置构建插件对象。

type DefinitionOf

type DefinitionOf[T any] struct {
	// contains filtered or unexported fields
}

DefinitionOf 是一个 typed config 插件定义。

func Define

func Define[T any](spec Spec[T]) DefinitionOf[T]

Define 创建 typed config 插件定义。

func (DefinitionOf[T]) Build

func (d DefinitionOf[T]) Build() (Plugin, error)

Build 使用默认配置创建插件对象,主要供嵌入式程序和插件测试使用。

func (DefinitionOf[T]) BuildWith

func (d DefinitionOf[T]) BuildWith(config T) (Plugin, error)

BuildWith 使用给定配置创建插件对象,主要供插件测试和嵌入式程序使用。

func (DefinitionOf[T]) Factory

func (d DefinitionOf[T]) Factory() Factory

Factory 返回可供运行框架注册的插件工厂。

func (DefinitionOf[T]) Manifest

func (d DefinitionOf[T]) Manifest() Manifest

Manifest 返回插件清单。

type Dialogue

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

Dialogue 是 SDK 提供的多轮对话控制器。

func (*Dialogue) Active

func (d *Dialogue) Active(c *EventContext) (DialogueSnapshot, bool, error)

Active 返回当前事件所在会话中的对话状态。

func (*Dialogue) Begin

func (d *Dialogue) Begin(c *EventContext, step string, data any) error

Begin 将当前事件所在会话推进到指定对话步骤。

func (*Dialogue) BeginText

func (d *Dialogue) BeginText(c *EventContext, step string, data any, prompt string) error

BeginText 开始对话并回复一条提示文本。

func (*Dialogue) End

func (d *Dialogue) End(c *EventContext) error

End 清除当前事件所在会话中的对话状态。

func (*Dialogue) Name

func (d *Dialogue) Name() string

Name 返回对话控制器名称。

func (*Dialogue) Route

func (d *Dialogue) Route() *Route

Route 返回恢复对话所使用的路由,便于高级插件进一步命名或调优。

func (*Dialogue) Step

func (d *Dialogue) Step(name string, handler DialogueHandler) *Dialogue

Step 注册一个对话步骤处理函数。

type DialogueHandler

type DialogueHandler func(*DialogueTurn) error

DialogueHandler 处理一个已恢复的对话步骤。

type DialogueOption

type DialogueOption func(*dialogueOptions)

DialogueOption 配置 SDK 多轮对话。

func DialogueWithPriority

func DialogueWithPriority(priority int) DialogueOption

DialogueWithPriority 设置恢复对话的路由优先级;默认优先于普通命令和消息路由。

func DialogueWithRules

func DialogueWithRules(rules ...Rule) DialogueOption

DialogueWithRules 为恢复中的对话追加约束规则,例如 ToMe 或 NotFromSelf。

func DialogueWithScope

func DialogueWithScope(scope DialogueScope) DialogueOption

DialogueWithScope 设置对话状态绑定的会话维度。

func DialogueWithTTL

func DialogueWithTTL(ttl time.Duration) DialogueOption

DialogueWithTTL 设置对话状态的过期时间;零值表示不过期。

type DialogueScope

type DialogueScope int

DialogueScope 描述多轮对话状态绑定的会话维度。

const (
	// DialogueScopeConversation 将状态绑定到当前自然会话,默认用于一对一的多轮聊天。
	DialogueScopeConversation DialogueScope = iota
	// DialogueScopeUser 将状态绑定到用户维度,适合跨群或跨频道延续的私有偏好流程。
	DialogueScopeUser
	// DialogueScopeGroup 将状态绑定到群或频道维度,适合多人共同推进的群聊流程。
	DialogueScopeGroup
)

type DialogueSnapshot

type DialogueSnapshot struct {
	Name      string
	Step      string
	Data      json.RawMessage
	CreatedAt time.Time
	UpdatedAt time.Time
}

DialogueSnapshot 是对话状态的只读快照。

type DialogueTurn

type DialogueTurn struct {
	*EventContext
	// contains filtered or unexported fields
}

DialogueTurn 是一次已恢复对话步骤的处理上下文。

func (*DialogueTurn) Dialogue

func (t *DialogueTurn) Dialogue() *Dialogue

Dialogue 返回当前对话控制器。

func (*DialogueTurn) End

func (t *DialogueTurn) End() error

End 清除当前会话中的对话状态。

func (*DialogueTurn) EndText

func (t *DialogueTurn) EndText(text string) error

EndText 清除对话状态并回复一条文本。

func (*DialogueTurn) Load

func (t *DialogueTurn) Load(out any) error

Load 将当前步骤携带的数据解码到 out。

func (*DialogueTurn) Next

func (t *DialogueTurn) Next(step string, data any) error

Next 将当前会话推进到另一个步骤,并替换步骤数据。

func (*DialogueTurn) NextText

func (t *DialogueTurn) NextText(step string, data any, prompt string) error

NextText 推进到另一个步骤并回复一条提示文本。

func (*DialogueTurn) State

func (t *DialogueTurn) State() DialogueSnapshot

State 返回当前对话状态快照。

func (*DialogueTurn) Step

func (t *DialogueTurn) Step() string

Step 返回当前正在处理的对话步骤名。

type EmitFunc

type EmitFunc = core.EmitFunc

EmitFunc 是适配器向运行时投递标准化事件的函数。

type Environment

type Environment struct {
	DataDir               string
	PluginID              string
	ConfigStore           ConfigStore
	AllowGlobalMiddleware bool
}

Environment 描述运行框架授予插件的宿主能力。

type ErrorHandler

type ErrorHandler func(*EventContext, error)

ErrorHandler 处理插件路由处理函数或中间件返回的错误。

type Event

type Event = core.Event

Event 是协议标准化后的事件。

type EventContext

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

EventContext 是插件事件处理函数的上下文。

func NewTestContext

func NewTestContext(app *App, event *Event) *EventContext

NewTestContext 创建测试用事件上下文。

func (*EventContext) Args

func (c *EventContext) Args() string

Args 返回命令名之后的原始参数文本。

func (*EventContext) Argv

func (c *EventContext) Argv() []string

Argv 返回按空白拆分后的命令参数。

func (*EventContext) Command

func (c *EventContext) Command() string

Command 返回命令规则匹配到的命令名。

func (*EventContext) Context

func (c *EventContext) Context() context.Context

Context 返回当前事件处理链使用的标准 context。

func (*EventContext) ConversationID

func (c *EventContext) ConversationID() string

ConversationID 返回当前事件对应的会话键。

func (*EventContext) Event

func (c *EventContext) Event() *Event

Event 返回当前正在处理的标准化事件。

func (*EventContext) Get

func (c *EventContext) Get(key string) (any, bool)

Get 读取当前插件处理链内的局部值。

func (*EventContext) GroupID

func (c *EventContext) GroupID() string

GroupID 返回当前事件的群 ID。

func (*EventContext) GroupRole added in v1.2.0

func (c *EventContext) GroupRole() string

GroupRole 返回当前事件发送者在群内的标准角色,例如 owner、manager 或 member。

func (*EventContext) HasAnyPermission added in v1.2.0

func (c *EventContext) HasAnyPermission(permissions ...string) bool

HasAnyPermission 判断当前事件是否满足任一标准权限标识。

func (*EventContext) HasPermission added in v1.2.0

func (c *EventContext) HasPermission(permission string) bool

HasPermission 判断当前事件是否满足一项标准权限标识。

func (*EventContext) IsGroup

func (c *EventContext) IsGroup() bool

IsGroup 判断当前事件是否为群消息。

func (*EventContext) IsPrivate

func (c *EventContext) IsPrivate() bool

IsPrivate 判断当前事件是否为私聊消息。

func (*EventContext) Match

func (c *EventContext) Match() Match

Match 返回当前路由的匹配详情。

func (*EventContext) Pass

func (c *EventContext) Pass() error

Pass 跳过当前路由且不视为失败。

func (*EventContext) RawEvent

func (c *EventContext) RawEvent() any

RawEvent 返回适配器保留的原始协议事件对象。

func (*EventContext) Reply

func (c *EventContext) Reply(chain message.Chain) (MessageReceipt, error)

Reply 使用事件的自然目标发送消息。

func (*EventContext) ReplyText

func (c *EventContext) ReplyText(text string) (MessageReceipt, error)

ReplyText 使用事件的自然目标发送纯文本回复。

func (*EventContext) RouteName

func (c *EventContext) RouteName() string

RouteName 返回当前路由的诊断名称。

func (*EventContext) SelfID

func (c *EventContext) SelfID() string

SelfID 返回当前机器人账号 ID。

func (*EventContext) Set

func (c *EventContext) Set(key string, value any)

Set 写入当前插件处理链内可见的局部值。

func (*EventContext) Stop

func (c *EventContext) Stop()

Stop 停止当前事件继续传播到后续路由。

func (*EventContext) StopError

func (c *EventContext) StopError() error

StopError 返回可用于处理函数的停止错误,同时标记当前上下文已停止。

func (*EventContext) Stopped

func (c *EventContext) Stopped() bool

Stopped 报告当前事件是否已被要求停止传播。

func (*EventContext) String

func (c *EventContext) String(key string) string

String 读取当前插件处理链内的字符串局部值。

func (*EventContext) Target

func (c *EventContext) Target() ReplyTarget

Target 返回当前事件的自然回复目标。

func (*EventContext) Text

func (c *EventContext) Text() string

Text 返回事件中的文本内容。

func (*EventContext) UnsafeCoreContext

func (c *EventContext) UnsafeCoreContext() *core.Context

UnsafeCoreContext 返回底层 core.Context。普通插件不应依赖它;它只适合协议适配、诊断或迁移代码。

func (*EventContext) UserID

func (c *EventContext) UserID() string

UserID 返回当前事件的用户 ID。

func (*EventContext) Var

func (c *EventContext) Var(key string) (any, bool)

Var 读取当前规则匹配写入的变量。

func (*EventContext) VarString

func (c *EventContext) VarString(key string) string

VarString 读取当前规则匹配写入的字符串变量。

type Factory

type Factory struct {
	Info     Manifest
	PluginID string
	Default  any
	Build    func(yaml.Node) (Plugin, error)
}

Factory 根据框架配置创建插件对象。

func (Factory) WithPluginID

func (f Factory) WithPluginID(id string) Factory

WithPluginID 返回使用指定本地插件 ID 的工厂。

type FileStore

type FileStore = core.FileStore

FileStore 是 goroutine 安全的文件持久化 Store。

func NewFileStore

func NewFileStore(path string) (*FileStore, error)

NewFileStore 打开或创建一个 JSON 文件存储。

type Handler

type Handler func(*EventContext) error

Handler 处理已经匹配成功的插件事件。

type Hook

type Hook = core.Hook

Hook 是 App 生命周期钩子函数。

type InstallOption

type InstallOption func(*Environment)

InstallOption 调整本次插件安装使用的宿主能力。

func WithConfigStore

func WithConfigStore(store ConfigStore) InstallOption

WithConfigStore 注入插件配置写回能力;通常由框架配置文件加载层使用。

func WithDataDir

func WithDataDir(root string) InstallOption

WithDataDir 注入插件数据根目录;运行框架会在其下为每个插件 ID 创建独立目录。

func WithEnvironment

func WithEnvironment(env Environment) InstallOption

WithEnvironment 注入完整宿主能力,供 host 统一安装插件时使用。

func WithPluginID

func WithPluginID(id string) InstallOption

WithPluginID 注入当前插件的本地安装 ID;状态、配置和数据目录都使用它定位。

type Manifest

type Manifest struct {
	Name        string
	Version     string
	Description string
}

Manifest 描述插件作者提供的展示信息。

type Match

type Match = core.Match

Match 描述规则匹配结果。

type MemoryStore

type MemoryStore = core.MemoryStore

MemoryStore 是 goroutine 安全的进程内 Store。

func NewMemoryStore

func NewMemoryStore() *MemoryStore

NewMemoryStore 创建默认内存存储。

type MessageReceipt

type MessageReceipt = core.MessageReceipt

MessageReceipt 是协议无关的消息发送回执。

type Middleware

type Middleware func(Handler) Handler

Middleware 包装插件处理函数。

func OnlyGroup

func OnlyGroup() Middleware

OnlyGroup 仅允许群消息进入后续处理链。

func OnlyPrivate

func OnlyPrivate() Middleware

OnlyPrivate 仅允许私聊消息进入后续处理链。

func RateLimit

func RateLimit(limit int, window time.Duration) Middleware

RateLimit 按会话限制事件处理频率。

func RateLimitBy

func RateLimitBy(limit int, window time.Duration, keyFunc func(*EventContext) string) Middleware

RateLimitBy 使用自定义键做进程内限速。

func Recover

func Recover(loggers ...*slog.Logger) Middleware

Recover 捕获处理链中的 panic。

func RequireAdmin

func RequireAdmin(ids ...string) Middleware

RequireAdmin 使用插件配置中的管理员列表鉴权;列表为空时回退到框架超级用户。

func RequirePermission added in v1.2.0

func RequirePermission(permissions ...string) Middleware

RequirePermission 仅允许满足任一标准权限标识的事件进入后续处理链。

func RequireSuperUser

func RequireSuperUser() Middleware

RequireSuperUser 只允许框架级超级用户继续执行。

func SuperUser

func SuperUser(ids ...any) Middleware

SuperUser 仅允许指定用户进入后续处理链。

func Timeout

func Timeout(timeout time.Duration) Middleware

Timeout 为后续处理函数派生带超时的 context。

func Trace

func Trace(loggers ...*slog.Logger) Middleware

Trace 记录路由处理耗时和事件关键信息。

type Observer

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

Observer 是插件 ID 命名空间下的一条旁路事件观察规则。

func (*Observer) Handle

func (o *Observer) Handle(handler ObserverHandler) *Observer

Handle 设置观察者处理函数。

func (*Observer) Name

func (o *Observer) Name(name string) *Observer

Name 设置观察者名称,名称会自动落入当前插件命名空间。

type ObserverHandler

type ObserverHandler = core.ObserverHandler

ObserverHandler 异步观察事件,不参与路由控制。

type Option

type Option = core.Option

Option 调整底层运行时配置,常用于插件测试。

func WithAdapter

func WithAdapter(adapter Adapter) Option

WithAdapter 配置运行时使用的协议适配器。

func WithLogger

func WithLogger(logger *slog.Logger) Option

WithLogger 配置测试或嵌入式运行时使用的日志器。

func WithStore

func WithStore(store Store) Option

WithStore 配置测试或嵌入式运行时使用的会话存储。

func WithSuperUsers

func WithSuperUsers(ids ...string) Option

WithSuperUsers 配置测试或嵌入式运行时的超级用户 ID。

type PanicError

type PanicError = core.PanicError

PanicError 包装处理函数或中间件中恢复到的 panic 值和调用栈。

type Plugin

type Plugin interface {
	Manifest() Manifest
	Setup(*Context) error
}

Plugin 是运行框架已经完成配置解析后可安装的插件对象。

type Protocol

type Protocol = core.Protocol

Protocol 是协议标识。

type Registry

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

Registry 保存运行框架可加载的插件工厂。

func NewRegistry

func NewRegistry() Registry

NewRegistry 创建空插件注册表。

func (Registry) Factory

func (r Registry) Factory(id string) (Factory, bool)

Factory 返回指定插件 ID 的工厂。

func (Registry) PluginIDs

func (r Registry) PluginIDs() []string

PluginIDs 返回按字典序排序的已注册插件 ID。

func (Registry) Plugins

func (r Registry) Plugins() []Manifest

Plugins 返回按插件 ID 排序的插件清单。

func (Registry) Register

func (r Registry) Register(factory Factory) error

Register 注册插件工厂。

type ReplyTarget

type ReplyTarget = core.ReplyTarget

ReplyTarget 描述主动消息的发送目标。

type Route

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

Route 是插件 ID 命名空间下的一条事件路由。

func (*Route) Handle

func (r *Route) Handle(handler Handler) *Route

Handle 设置路由处理函数。

func (*Route) Name

func (r *Route) Name(name string) *Route

Name 设置路由名称,名称会自动落入当前插件命名空间。

func (*Route) Priority

func (r *Route) Priority(priority int) *Route

Priority 设置路由优先级;数值越大越先执行,同优先级保持注册顺序。

func (*Route) Use

func (r *Route) Use(middleware ...Middleware) *Route

Use 追加只作用于当前路由的中间件。

type Rule

type Rule interface {
	Match(context.Context, *EventContext) (Match, bool)
}

Rule 判断插件路由是否应处理当前事件。

func All

func All(rules ...Rule) Rule

All 要求所有规则都匹配。

func AllowedGroups

func AllowedGroups(ids ...string) Rule

AllowedGroups 按配置中的群 ID 列表限制群消息;私聊等非群消息不受影响,列表为空时不限制。

func Any

func Any() Rule

Any 匹配所有事件。

func AnyOf

func AnyOf(rules ...Rule) Rule

AnyOf 在任意规则匹配时通过。

func CommandRule

func CommandRule(names ...string) Rule

CommandRule 使用默认前缀匹配命令。

func CommandWithPrefixes

func CommandWithPrefixes(prefixes []string, names ...string) Rule

CommandWithPrefixes 使用显式前缀集合匹配命令。

func Contains

func Contains(substr string) Rule

Contains 匹配包含指定文本的消息。

func DetailType

func DetailType(kind string) Rule

DetailType 匹配标准化事件细分类型。

func EventType

func EventType(kind string) Rule

EventType 匹配标准化事件类型。

func FromSelf

func FromSelf() Rule

FromSelf 匹配由当前机器人账号自己发送的消息。

func FromUser

func FromUser(ids ...any) Rule

FromUser 匹配指定发送者 ID。

func Group

func Group() Rule

Group 匹配群消息。

func InGroup

func InGroup(ids ...any) Rule

InGroup 匹配指定群 ID。

func Mentioned

func Mentioned(ids ...any) Rule

Mentioned 匹配提及指定用户的消息;未传 ID 时匹配任意提及。

func MessageEvent

func MessageEvent() Rule

MessageEvent 匹配消息事件。

func Not

func Not(rule Rule) Rule

Not 在规则不匹配时通过。

func NotFromSelf

func NotFromSelf() Rule

NotFromSelf 排除当前机器人账号自己发送的消息。

func Permission added in v1.2.0

func Permission(permissions ...string) Rule

Permission 匹配满足任一标准权限标识的事件。

func Prefix

func Prefix(prefix string) Rule

Prefix 匹配指定前缀的消息。

func Private

func Private() Rule

Private 匹配私聊消息。

func RegexRule

func RegexRule(pattern string) Rule

RegexRule 使用正则表达式字符串匹配事件文本。

func RegexpRule

func RegexpRule(re *regexp.Regexp) Rule

RegexpRule 使用已编译的正则表达式匹配事件文本。

func ToMe

func ToMe() Rule

ToMe 匹配提及机器人或私聊消息。

type RuleFunc

type RuleFunc func(context.Context, *EventContext) (Match, bool)

RuleFunc 将普通函数适配为 Rule。

func (RuleFunc) Match

func (f RuleFunc) Match(ctx context.Context, c *EventContext) (Match, bool)

Match 调用底层函数完成规则匹配。

type Session

type Session = core.Session

Session 是基于固定键前缀的 Store 视图。

func NewSession

func NewSession(store Store, key string) *Session

NewSession 创建指定键前缀下的会话视图。

type SetupFunc

type SetupFunc[T any] func(*Context, T) error

SetupFunc 是 typed config 插件的安装函数。

type Spec

type Spec[T any] struct {
	// Manifest 是插件展示信息;Name 不承担配置或状态命名空间职责。
	Manifest Manifest

	// DefaultConfig 是宿主首次同步插件配置时写入的默认部署配置。
	DefaultConfig T

	// Setup 是宿主解析配置后调用的安装入口。
	Setup SetupFunc[T]
}

Spec 描述一个 typed config 插件定义。

type State

type State[T any] struct {
	// contains filtered or unexported fields
}

State 是绑定到 PluginID 命名空间和事件上下文的一段 typed 会话状态。

func ConversationState

func ConversationState[T any](ctx *Context, event *EventContext, key string) State[T]

ConversationState 返回当前自然会话下的 typed 状态。

func GroupState

func GroupState[T any](ctx *Context, event *EventContext, key string) State[T]

GroupState 返回当前群或频道维度下的 typed 状态。非群或频道事件会返回 ErrGroupContextUnavailable,插件应在群路由或确认 event.GroupID() 非空后使用。

func NamedState

func NamedState[T any](ctx *Context, event *EventContext, key, scope string) State[T]

NamedState 返回当前插件自定义维度下的 typed 状态。

func UserState

func UserState[T any](ctx *Context, event *EventContext, key string) State[T]

UserState 返回当前用户维度下的 typed 状态。

func (State[T]) Delete

func (s State[T]) Delete() error

Delete 删除状态。

func (State[T]) Load

func (s State[T]) Load() (T, bool, error)

Load 读取状态;状态不存在时返回零值和 ok=false。

func (State[T]) LoadOr

func (s State[T]) LoadOr(fallback T) (T, error)

LoadOr 读取状态;状态不存在时返回 fallback。

func (State[T]) Save

func (s State[T]) Save(value T, ttl time.Duration) error

Save 写入状态。ttl 大于 0 时,状态会在到期后失效。

func (State[T]) Update

func (s State[T]) Update(fallback T, ttl time.Duration, update func(*T) error) (T, error)

Update 读取状态,交给 update 原地修改后再写回。该操作简化调用但不提供跨事件 原子性;强一致计数、库存或积分应使用插件自管数据库。 状态不存在时从 fallback 开始;ttl 大于 0 时,写回后的状态会在到期后失效。

type Store

type Store = core.Store

Store 是会话存储接口。

type TaskFunc

type TaskFunc = core.TaskFunc

TaskFunc 是生命周期托管任务函数。

type TaskOption

type TaskOption = core.TaskOption

TaskOption 配置生命周期托管任务。

func TaskCritical

func TaskCritical() TaskOption

TaskCritical 让任务失败时停止 App.Run,并把任务错误作为运行错误返回。

func TaskImmediate

func TaskImmediate() TaskOption

TaskImmediate 让周期任务启动后立即执行一次。

Directories

Path Synopsis
Package message 为插件 SDK 用户暴露 AnyBot 的协议中立消息模型。
Package message 为插件 SDK 用户暴露 AnyBot 的协议中立消息模型。
testkit 包提供插件单元测试用的轻量 AnyBot 运行时。
testkit 包提供插件单元测试用的轻量 AnyBot 运行时。

Jump to

Keyboard shortcuts

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