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 ¶
- Variables
- func Install(app *App, plugins ...Plugin) error
- func InstallCoreWith(app *core.App, env Environment, plugin Plugin) error
- func InstallDefault(app *App, definitions ...Definition) error
- func InstallDefaultWith(app *App, env Environment, definition Definition) error
- func InstallDefaultWithID(app *App, id string, definition Definition) error
- func InstallWith(app *App, env Environment, plugin Plugin) error
- func InstallWithID(app *App, id string, plugin Plugin) error
- func ParseConfigPath(input string) ([]string, error)
- func ValidatePluginID(id string) error
- type ActionClient
- type Adapter
- type AdapterState
- type AdapterStateHook
- type App
- type ConfigAssignment
- type ConfigHandle
- type ConfigStore
- type Context
- func (c *Context) Client() ActionClient
- func (c *Context) Command(names ...string) *Route
- func (c *Context) Config() ConfigHandle
- func (c *Context) DataDir() (string, error)
- func (c *Context) Dialogue(name string, opts ...DialogueOption) *Dialogue
- func (c *Context) Every(name string, interval time.Duration, fn TaskFunc, opts ...TaskOption)
- func (c *Context) Go(name string, fn TaskFunc, opts ...TaskOption)
- func (c *Context) GoWhenActionReady(name string, fn TaskFunc, opts ...TaskOption)
- func (c *Context) GroupSession(event *EventContext) *Session
- func (c *Context) Logger() *slog.Logger
- func (c *Context) Manifest() Manifest
- func (c *Context) Observe(rules ...Rule) *Observer
- func (c *Context) On(rules ...Rule) *Route
- func (c *Context) OnAdapterState(hook AdapterStateHook)
- func (c *Context) OnMessage(rules ...Rule) *Route
- func (c *Context) OnReady(hook Hook)
- func (c *Context) OnShutdown(hook Hook)
- func (c *Context) OnStart(hook Hook)
- func (c *Context) PluginID() string
- func (c *Context) Send(ctx context.Context, target ReplyTarget, chain message.Chain) (MessageReceipt, error)
- func (c *Context) SendText(ctx context.Context, target ReplyTarget, text string) (MessageReceipt, error)
- func (c *Context) Session(event *EventContext) *Session
- func (c *Context) SessionBy(key string) *Session
- func (c *Context) Store() Store
- func (c *Context) Use(middleware ...Middleware)
- func (c *Context) UseGlobal(middleware ...Middleware) error
- func (c *Context) UserSession(event *EventContext) *Session
- func (c *Context) WaitActionReady(ctx context.Context) error
- type Definition
- type DefinitionOf
- type Dialogue
- func (d *Dialogue) Active(c *EventContext) (DialogueSnapshot, bool, error)
- func (d *Dialogue) Begin(c *EventContext, step string, data any) error
- func (d *Dialogue) BeginText(c *EventContext, step string, data any, prompt string) error
- func (d *Dialogue) End(c *EventContext) error
- func (d *Dialogue) Name() string
- func (d *Dialogue) Route() *Route
- func (d *Dialogue) Step(name string, handler DialogueHandler) *Dialogue
- type DialogueHandler
- type DialogueOption
- type DialogueScope
- type DialogueSnapshot
- type DialogueTurn
- func (t *DialogueTurn) Dialogue() *Dialogue
- func (t *DialogueTurn) End() error
- func (t *DialogueTurn) EndText(text string) error
- func (t *DialogueTurn) Load(out any) error
- func (t *DialogueTurn) Next(step string, data any) error
- func (t *DialogueTurn) NextText(step string, data any, prompt string) error
- func (t *DialogueTurn) State() DialogueSnapshot
- func (t *DialogueTurn) Step() string
- type EmitFunc
- type Environment
- type ErrorHandler
- type Event
- type EventContext
- func (c *EventContext) Args() string
- func (c *EventContext) Argv() []string
- func (c *EventContext) Command() string
- func (c *EventContext) Context() context.Context
- func (c *EventContext) ConversationID() string
- func (c *EventContext) Event() *Event
- func (c *EventContext) Get(key string) (any, bool)
- func (c *EventContext) GroupID() string
- func (c *EventContext) GroupRole() string
- func (c *EventContext) HasAnyPermission(permissions ...string) bool
- func (c *EventContext) HasPermission(permission string) bool
- func (c *EventContext) IsGroup() bool
- func (c *EventContext) IsPrivate() bool
- func (c *EventContext) Match() Match
- func (c *EventContext) Pass() error
- func (c *EventContext) RawEvent() any
- func (c *EventContext) Reply(chain message.Chain) (MessageReceipt, error)
- func (c *EventContext) ReplyText(text string) (MessageReceipt, error)
- func (c *EventContext) RouteName() string
- func (c *EventContext) SelfID() string
- func (c *EventContext) Set(key string, value any)
- func (c *EventContext) Stop()
- func (c *EventContext) StopError() error
- func (c *EventContext) Stopped() bool
- func (c *EventContext) String(key string) string
- func (c *EventContext) Target() ReplyTarget
- func (c *EventContext) Text() string
- func (c *EventContext) UnsafeCoreContext() *core.Context
- func (c *EventContext) UserID() string
- func (c *EventContext) Var(key string) (any, bool)
- func (c *EventContext) VarString(key string) string
- type Factory
- type FileStore
- type Handler
- type Hook
- type InstallOption
- type Manifest
- type Match
- type MemoryStore
- type MessageReceipt
- type Middleware
- func OnlyGroup() Middleware
- func OnlyPrivate() Middleware
- func RateLimit(limit int, window time.Duration) Middleware
- func RateLimitBy(limit int, window time.Duration, keyFunc func(*EventContext) string) Middleware
- func Recover(loggers ...*slog.Logger) Middleware
- func RequireAdmin(ids ...string) Middleware
- func RequirePermission(permissions ...string) Middleware
- func RequireSuperUser() Middleware
- func SuperUser(ids ...any) Middleware
- func Timeout(timeout time.Duration) Middleware
- func Trace(loggers ...*slog.Logger) Middleware
- type Observer
- type ObserverHandler
- type Option
- type PanicError
- type Plugin
- type Protocol
- type Registry
- type ReplyTarget
- type Route
- type Rule
- func All(rules ...Rule) Rule
- func AllowedGroups(ids ...string) Rule
- func Any() Rule
- func AnyOf(rules ...Rule) Rule
- func CommandRule(names ...string) Rule
- func CommandWithPrefixes(prefixes []string, names ...string) Rule
- func Contains(substr string) Rule
- func DetailType(kind string) Rule
- func EventType(kind string) Rule
- func FromSelf() Rule
- func FromUser(ids ...any) Rule
- func Group() Rule
- func InGroup(ids ...any) Rule
- func Mentioned(ids ...any) Rule
- func MessageEvent() Rule
- func Not(rule Rule) Rule
- func NotFromSelf() Rule
- func Permission(permissions ...string) Rule
- func Prefix(prefix string) Rule
- func Private() Rule
- func RegexRule(pattern string) Rule
- func RegexpRule(re *regexp.Regexp) Rule
- func ToMe() Rule
- type RuleFunc
- type Session
- type SetupFunc
- type Spec
- type State
- func ConversationState[T any](ctx *Context, event *EventContext, key string) State[T]
- func GroupState[T any](ctx *Context, event *EventContext, key string) State[T]
- func NamedState[T any](ctx *Context, event *EventContext, key, scope string) State[T]
- func UserState[T any](ctx *Context, event *EventContext, key string) State[T]
- type Store
- type TaskFunc
- type TaskOption
Constants ¶
This section is empty.
Variables ¶
var ( ErrActionUnavailable = core.ErrActionUnavailable ErrReplyTargetUnavailable = core.ErrReplyTargetUnavailable ErrSessionUnavailable = core.ErrSessionUnavailable // ErrPass 表示当前路由主动让出处理权。 ErrPass = core.ErrPass // ErrStop 表示当前事件应停止向后续路由传播。 ErrStop = core.ErrStop ErrUnauthorized = core.ErrUnauthorized // ErrRateLimited 表示当前限速窗口已被耗尽。 ErrRateLimited = core.ErrRateLimited )
ErrConfigStoreUnavailable 表示当前运行时没有配置可写的插件配置存储。
ErrDataDirUnavailable 表示当前运行时没有配置插件数据目录。
ErrEventContextUnavailable 表示当前缺少事件上下文。
ErrGlobalMiddlewareUnavailable 表示宿主没有授予插件注册全局中间件的能力。
ErrGroupContextUnavailable 表示当前事件没有群或频道上下文。
var ErrStateKeyRequired = errors.New("anybot: plugin state key is required")
ErrStateKeyRequired 表示 typed 状态缺少字段名。
ErrStoreUnavailable 表示当前运行时没有可用会话存储。
Functions ¶
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 ¶
InstallWithID 使用显式稳定 PluginID 安装已构建好的插件对象。
func ParseConfigPath ¶
ParseConfigPath 解析插件 config 下的点分字段路径。
func ValidatePluginID ¶
ValidatePluginID 校验 PluginID 是否符合 AnyBot 生成的随机安装 ID 形态。
Types ¶
type App ¶
type App struct {
// contains filtered or unexported fields
}
App 是 SDK 暴露的运行时句柄,常用于插件测试和嵌入式程序。
type ConfigAssignment ¶
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) 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) Dialogue ¶
func (c *Context) Dialogue(name string, opts ...DialogueOption) *Dialogue
Dialogue 创建插件命名空间内的多轮对话控制器,并注册用于恢复对话的高优先级消息路由。
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) OnAdapterState ¶
func (c *Context) OnAdapterState(hook AdapterStateHook)
OnAdapterState 注册动作通道状态钩子。
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) 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 命名空间下的用户存储视图。
type Definition ¶
Definition 是插件定义,可转成运行框架工厂,也可用默认配置构建插件对象。
type DefinitionOf ¶
type DefinitionOf[T any] struct { // contains filtered or unexported fields }
DefinitionOf 是一个 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 返回可供运行框架注册的插件工厂。
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 将当前事件所在会话推进到指定对话步骤。
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) EndText ¶
func (t *DialogueTurn) EndText(text string) error
EndText 清除对话状态并回复一条文本。
func (*DialogueTurn) Next ¶
func (t *DialogueTurn) Next(step string, data any) error
Next 将当前会话推进到另一个步骤,并替换步骤数据。
type Environment ¶
type Environment struct {
DataDir string
PluginID string
ConfigStore ConfigStore
AllowGlobalMiddleware bool
}
Environment 描述运行框架授予插件的宿主能力。
type EventContext ¶
type EventContext struct {
// contains filtered or unexported fields
}
EventContext 是插件事件处理函数的上下文。
func NewTestContext ¶
func NewTestContext(app *App, event *Event) *EventContext
NewTestContext 创建测试用事件上下文。
func (*EventContext) Context ¶
func (c *EventContext) Context() context.Context
Context 返回当前事件处理链使用的标准 context。
func (*EventContext) ConversationID ¶
func (c *EventContext) ConversationID() string
ConversationID 返回当前事件对应的会话键。
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) 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) StopError ¶
func (c *EventContext) StopError() error
StopError 返回可用于处理函数的停止错误,同时标记当前上下文已停止。
func (*EventContext) String ¶
func (c *EventContext) String(key string) string
String 读取当前插件处理链内的字符串局部值。
func (*EventContext) UnsafeCoreContext ¶
func (c *EventContext) UnsafeCoreContext() *core.Context
UnsafeCoreContext 返回底层 core.Context。普通插件不应依赖它;它只适合协议适配、诊断或迁移代码。
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 ¶
WithPluginID 返回使用指定本地插件 ID 的工厂。
type FileStore ¶
FileStore 是 goroutine 安全的文件持久化 Store。
func NewFileStore ¶
NewFileStore 打开或创建一个 JSON 文件存储。
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 Middleware ¶
Middleware 包装插件处理函数。
func RateLimitBy ¶
func RateLimitBy(limit int, window time.Duration, keyFunc func(*EventContext) string) Middleware
RateLimitBy 使用自定义键做进程内限速。
func RequireAdmin ¶
func RequireAdmin(ids ...string) Middleware
RequireAdmin 使用插件配置中的管理员列表鉴权;列表为空时回退到框架超级用户。
func RequirePermission ¶ added in v1.2.0
func RequirePermission(permissions ...string) Middleware
RequirePermission 仅允许满足任一标准权限标识的事件进入后续处理链。
type Observer ¶
type Observer struct {
// contains filtered or unexported fields
}
Observer 是插件 ID 命名空间下的一条旁路事件观察规则。
func (*Observer) Handle ¶
func (o *Observer) Handle(handler ObserverHandler) *Observer
Handle 设置观察者处理函数。
type Registry ¶
type Registry struct {
// contains filtered or unexported fields
}
Registry 保存运行框架可加载的插件工厂。
type Route ¶
type Route struct {
// contains filtered or unexported fields
}
Route 是插件 ID 命名空间下的一条事件路由。
type Rule ¶
type Rule interface {
Match(context.Context, *EventContext) (Match, bool)
}
Rule 判断插件路由是否应处理当前事件。
func AllowedGroups ¶
AllowedGroups 按配置中的群 ID 列表限制群消息;私聊等非群消息不受影响,列表为空时不限制。
func CommandWithPrefixes ¶
CommandWithPrefixes 使用显式前缀集合匹配命令。
func Permission ¶ added in v1.2.0
Permission 匹配满足任一标准权限标识的事件。
type RuleFunc ¶
type RuleFunc func(context.Context, *EventContext) (Match, bool)
RuleFunc 将普通函数适配为 Rule。
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 状态。