Documentation
¶
Overview ¶
core 包提供机器人运行时、事件路由、中间件、会话存储、生命周期任务、 事件旁路观察、动作通道状态和协议适配核心。
core 是嵌入式程序和协议适配器使用的底层包。上层运行框架负责配置装配、 状态命名空间、持久化目录和运行编排。
Index ¶
- Variables
- func Configure(opts ...Option)
- func Every(name string, interval time.Duration, fn TaskFunc, opts ...TaskOption)
- func Go(name string, fn TaskFunc, opts ...TaskOption)
- func GoWhenActionReady(name string, fn TaskFunc, opts ...TaskOption)
- func OnAdapterState(hook AdapterStateHook)
- func OnError(handler ErrorHandler)
- func OnObserverError(handler ObserverErrorHandler)
- func OnReady(hook Hook)
- func OnShutdown(hook Hook)
- func OnStart(hook Hook)
- func OnStop(hook Hook)
- func ResetDefault(opts ...Option)
- func Run(ctxs ...context.Context) error
- func Use(middleware ...Middleware)
- func WaitActionReady(ctx context.Context) error
- type ActionClient
- type Adapter
- type AdapterState
- type AdapterStateHook
- type AdapterStateKind
- type AdapterStateSink
- type App
- func (a *App) Adapter() Adapter
- func (a *App) AdapterState() AdapterState
- func (a *App) Client() ActionClient
- func (a *App) Command(names ...string) *Route
- func (a *App) Dispatch(ctx context.Context, event *Event) error
- func (a *App) Every(name string, interval time.Duration, fn TaskFunc, opts ...TaskOption)
- func (a *App) Go(name string, fn TaskFunc, opts ...TaskOption)
- func (a *App) GoWhenActionReady(name string, fn TaskFunc, opts ...TaskOption)
- func (a *App) Group(rules ...Rule) *Router
- func (a *App) IsSuperUser(id any) bool
- func (a *App) Logger() *slog.Logger
- func (a *App) Observe(rules ...Rule) *Observer
- func (a *App) On(rules ...Rule) *Route
- func (a *App) OnAdapterState(hook AdapterStateHook)
- func (a *App) OnError(handler ErrorHandler)
- func (a *App) OnMessage(rules ...Rule) *Route
- func (a *App) OnObserverError(handler ObserverErrorHandler)
- func (a *App) OnReady(hook Hook)
- func (a *App) OnShutdown(hook Hook)
- func (a *App) OnStart(hook Hook)
- func (a *App) OnStop(hook Hook)
- func (a *App) Regex(pattern string) *Route
- func (a *App) Router() *Router
- func (a *App) Run(ctx context.Context) error
- func (a *App) Store() Store
- func (a *App) SuperUsers() []string
- func (a *App) Use(middleware ...Middleware)
- func (a *App) WaitActionReady(ctx context.Context) error
- type Context
- func (c *Context) Adapter() Adapter
- func (c *Context) App() *App
- func (c *Context) Args() string
- func (c *Context) Argv() []string
- func (c *Context) Client() ActionClient
- func (c *Context) Command() string
- func (c *Context) ConversationID() string
- func (c *Context) Event() *Event
- func (c *Context) Get(key string) (any, bool)
- func (c *Context) GroupID() string
- func (c *Context) GroupRole() string
- func (c *Context) GroupSession() *Session
- func (c *Context) HasAnyPermission(permissions ...string) bool
- func (c *Context) HasPermission(permission string) bool
- func (c *Context) IsGroup() bool
- func (c *Context) IsPrivate() bool
- func (c *Context) IsSuperUser() bool
- func (c *Context) Logger() *slog.Logger
- func (c *Context) Match() Match
- func (c *Context) Pass() error
- func (c *Context) RawEvent() any
- func (c *Context) Reply(chain message.Chain) (MessageReceipt, error)
- func (c *Context) ReplyText(text string) (MessageReceipt, error)
- func (c *Context) Route() *Route
- func (c *Context) RouteName() string
- func (c *Context) SelfID() string
- func (c *Context) Session() *Session
- func (c *Context) SessionBy(key string) *Session
- func (c *Context) Set(key string, value any)
- func (c *Context) Stop()
- func (c *Context) StopError() error
- func (c *Context) Stopped() bool
- func (c *Context) Store() Store
- func (c *Context) String(key string) string
- func (c *Context) Target() ReplyTarget
- func (c *Context) Text() string
- func (c *Context) UserID() string
- func (c *Context) UserSession() *Session
- func (c *Context) Var(key string) (any, bool)
- func (c *Context) VarString(key string) string
- type EmitFunc
- type ErrorHandler
- type Event
- type EventKeyFunc
- type FileStore
- func (s *FileStore) Delete(ctx context.Context, key string) error
- func (s *FileStore) Get(ctx context.Context, key string) ([]byte, bool, error)
- func (s *FileStore) Path() string
- func (s *FileStore) Set(ctx context.Context, key string, value []byte, ttl time.Duration) error
- func (s *FileStore) Sweep(ctx context.Context) error
- type Handler
- type Hook
- type Match
- type MemoryStore
- func (s *MemoryStore) Delete(ctx context.Context, key string) error
- func (s *MemoryStore) Get(ctx context.Context, key string) ([]byte, bool, error)
- func (s *MemoryStore) Set(ctx context.Context, key string, value []byte, ttl time.Duration) error
- func (s *MemoryStore) Sweep(ctx context.Context) error
- 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(*Context) string) Middleware
- func Recover(loggers ...*slog.Logger) Middleware
- func RequireSuperUser() Middleware
- func SuperUser(ids ...any) Middleware
- func Timeout(timeout time.Duration) Middleware
- func Trace(loggers ...*slog.Logger) Middleware
- type Observer
- type ObserverErrorHandler
- type ObserverHandler
- type Option
- func WithAdapter(adapter Adapter) Option
- func WithBuffer(size int) Option
- func WithErrorHandler(handler ErrorHandler) Option
- func WithLogger(logger *slog.Logger) Option
- func WithObserverBuffer(size int) Option
- func WithSerialBy(fn EventKeyFunc) Option
- func WithSerialByConversation() Option
- func WithStore(store Store) Option
- func WithSuperUsers(ids ...string) Option
- func WithWorkers(workers int) Option
- type PanicError
- type Protocol
- type ReplyTarget
- type Route
- type Router
- type Rule
- func All(rules ...Rule) 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
- func (s *Session) Delete(ctx context.Context, name string) error
- func (s *Session) Get(ctx context.Context, name string) ([]byte, bool, error)
- func (s *Session) Key() string
- func (s *Session) LoadJSON(ctx context.Context, name string, out any) (bool, error)
- func (s *Session) SaveJSON(ctx context.Context, name string, value any, ttl time.Duration) error
- func (s *Session) Set(ctx context.Context, name string, value []byte, ttl time.Duration) error
- type StatefulAdapter
- type Store
- type TaskFunc
- type TaskOption
Constants ¶
This section is empty.
Variables ¶
var ( // ErrPass 表示当前路由主动让出处理权,后续路由继续匹配。 ErrPass = errors.New("anybot: pass route") // ErrStop 表示当前事件应停止向后续路由传播。 ErrStop = errors.New("anybot: stop route") ErrUnauthorized = errors.New("anybot: unauthorized") // ErrRateLimited 表示当前限速窗口已被耗尽。 ErrRateLimited = errors.New("anybot: rate limited") ErrActionUnavailable = errors.New("anybot: action unavailable") ErrReplyTargetUnavailable = errors.New("anybot: reply target unavailable") ErrSessionUnavailable = errors.New("anybot: session unavailable") )
Functions ¶
func Every ¶
func Every(name string, interval time.Duration, fn TaskFunc, opts ...TaskOption)
Every 向默认 App 注册生命周期托管的周期任务。
func GoWhenActionReady ¶
func GoWhenActionReady(name string, fn TaskFunc, opts ...TaskOption)
GoWhenActionReady 向默认 App 注册等待动作客户端可用后执行的生命周期任务。
func OnAdapterState ¶
func OnAdapterState(hook AdapterStateHook)
OnAdapterState 向默认 App 注册适配器状态变化钩子。
func OnObserverError ¶
func OnObserverError(handler ObserverErrorHandler)
OnObserverError 向默认 App 注册观察者错误处理回调。
func WaitActionReady ¶
WaitActionReady 等待默认 App 的动作客户端可用。
Types ¶
type ActionClient ¶
type ActionClient interface {
Send(context.Context, ReplyTarget, message.Chain) (MessageReceipt, error)
}
ActionClient 定义协议无关的消息发送能力。
type Adapter ¶
type Adapter interface {
Protocol() Protocol
Start(context.Context, EmitFunc) error
Client() ActionClient
}
Adapter 把具体聊天协议接入 AnyBot 运行时。
type AdapterState ¶
type AdapterState struct {
Protocol Protocol
Kind AdapterStateKind
ActionReady bool
Transport string
Reason string
Err error
At time.Time
}
AdapterState 是协议无关的适配器动作通道状态。
func CurrentAdapterState ¶
func CurrentAdapterState() AdapterState
CurrentAdapterState 返回默认 App 最近一次已知的适配器状态。
type AdapterStateHook ¶
type AdapterStateHook func(context.Context, AdapterState)
AdapterStateHook 接收适配器动作通道状态变化。
type AdapterStateKind ¶
type AdapterStateKind string
AdapterStateKind 描述适配器动作通道的当前运行状态。
const ( // AdapterStateUnknown 表示运行时尚未收到适配器状态。 AdapterStateUnknown AdapterStateKind = "unknown" // AdapterStateStarting 表示适配器正在启动。 AdapterStateStarting AdapterStateKind = "starting" // AdapterStateReady 表示动作客户端当前可用。 AdapterStateReady AdapterStateKind = "ready" // AdapterStateDisconnected 表示动作客户端暂不可用,但运行时仍可能继续等待重连。 AdapterStateDisconnected AdapterStateKind = "disconnected" // AdapterStateStopped 表示适配器已经停止。 AdapterStateStopped AdapterStateKind = "stopped" )
type AdapterStateSink ¶
type AdapterStateSink func(context.Context, AdapterState)
AdapterStateSink 是适配器向运行时报告状态变化的函数。
type App ¶
type App struct {
// contains filtered or unexported fields
}
App 是 AnyBot 的运行时入口,负责连接适配器、调度事件并执行路由链。
func (*App) Go ¶
func (a *App) Go(name string, fn TaskFunc, opts ...TaskOption)
Go 注册一个随 App 生命周期启动和停止的后台任务。
func (*App) GoWhenActionReady ¶
func (a *App) GoWhenActionReady(name string, fn TaskFunc, opts ...TaskOption)
GoWhenActionReady 注册一个随 App 生命周期启动的后台任务。任务会先等待动作客户端 可用,再调用 fn;适合启动后主动发送消息、恢复投递队列等需要动作通道的场景。
func (*App) IsSuperUser ¶
IsSuperUser 判断给定用户 ID 是否属于当前 App 的超级用户。
func (*App) OnAdapterState ¶
func (a *App) OnAdapterState(hook AdapterStateHook)
OnAdapterState 注册适配器状态变化钩子。
func (*App) OnObserverError ¶
func (a *App) OnObserverError(handler ObserverErrorHandler)
OnObserverError 注册观察者错误处理器。
type Context ¶
Context 是路由处理函数的工作上下文,聚合事件、运行时能力、匹配结果和局部值。
func NewTestContext ¶
NewTestContext 创建测试用上下文;app 为空时会使用默认配置的新 App。
func (*Context) ConversationID ¶
ConversationID 返回当前事件对应的会话键,可直接用于会话存储。
func (*Context) GroupSession ¶
GroupSession 返回当前群或频道维度的存储视图。
func (*Context) HasAnyPermission ¶ added in v1.2.0
HasAnyPermission 判断当前事件是否满足任一标准权限标识。
func (*Context) HasPermission ¶ added in v1.2.0
HasPermission 判断当前事件是否满足一项标准权限标识。
支持的基础标识包括 all、user、private、group、group.member、 group.manager、group.owner 与 superuser。group.manager 包含群主。
func (*Context) IsSuperUser ¶
IsSuperUser 判断当前事件发送者是否属于当前 App 的超级用户。
func (*Context) Reply ¶
func (c *Context) Reply(chain message.Chain) (MessageReceipt, error)
Reply 使用事件的自然目标发送消息。
func (*Context) ReplyText ¶
func (c *Context) ReplyText(text string) (MessageReceipt, error)
ReplyText 使用事件的自然目标发送纯文本回复。
type Event ¶
type Event struct {
ID string
Protocol Protocol
SelfID string
Type string
DetailType string
SubType string
UserID string
GroupID string
GroupRole string
GuildID string
ChannelID string
Text string
Message message.Chain
Raw json.RawMessage
Data any
}
Event 是 AnyBot 的协议无关事件封套,保留常用标准字段和原始协议数据。
func (*Event) ConversationID ¶
ConversationID 返回适合会话存储的稳定键,优先按频道、群聊、私聊逐级区分。
func (*Event) GroupSessionID ¶
GroupSessionID 返回按群或频道维度隔离的存储键。
func (*Event) Target ¶
func (e *Event) Target() ReplyTarget
Target 返回该事件的自然回复目标,供 Context.Reply 和适配器发送消息使用。
type FileStore ¶
type FileStore struct {
// contains filtered or unexported fields
}
FileStore 是 goroutine 安全的文件持久化 Store,适合保存轻量会话状态。
func NewFileStore ¶
NewFileStore 打开或创建一个 JSON 文件存储。文件不存在时会在第一次写入时创建。
type MemoryStore ¶
type MemoryStore struct {
// contains filtered or unexported fields
}
MemoryStore 是 goroutine 安全的进程内 Store,适合短期会话状态。
func (*MemoryStore) Delete ¶
func (s *MemoryStore) Delete(ctx context.Context, key string) error
Delete 删除指定键。
type Middleware ¶
Middleware 包装处理函数,用于实现日志、鉴权、限速等横切能力。
func RateLimit ¶
func RateLimit(limit int, window time.Duration) Middleware
RateLimit 使用当前会话键做简单的进程内限速。
func RateLimitBy ¶
RateLimitBy 使用自定义键做进程内限速;键为空时回退到会话、用户或全局维度。
func Recover ¶
func Recover(loggers ...*slog.Logger) Middleware
Recover 捕获处理链中的 panic,记录调用栈,并把 panic 转成 PanicError。
func RequireSuperUser ¶
func RequireSuperUser() Middleware
RequireSuperUser 仅允许 App 级超级用户进入后续处理链,未授权时返回 ErrUnauthorized。
func SuperUser ¶
func SuperUser(ids ...any) Middleware
SuperUser 仅允许指定用户进入后续处理链,未授权时返回 ErrUnauthorized。
func Timeout ¶
func Timeout(timeout time.Duration) Middleware
Timeout 为后续处理函数派生带超时的 context;timeout 不大于 0 时不生效。
type Observer ¶
type Observer struct {
// contains filtered or unexported fields
}
Observer 表示一条事件旁路观察规则。
func (*Observer) Handle ¶
func (o *Observer) Handle(handler ObserverHandler) *Observer
Handle 设置观察者处理函数。
type ObserverErrorHandler ¶
ObserverErrorHandler 处理事件观察者返回的错误或 panic。
type ObserverHandler ¶
ObserverHandler 异步观察事件,不参与路由控制。
type Option ¶
type Option func(*App)
Option 调整 App 的运行时配置。
func WithErrorHandler ¶
func WithErrorHandler(handler ErrorHandler) Option
WithErrorHandler 注册错误处理器。
func WithObserverBuffer ¶
WithObserverBuffer 配置异步事件观察者的并发队列容量;不大于 0 的值会被忽略。
func WithSerialBy ¶
func WithSerialBy(fn EventKeyFunc) Option
WithSerialBy 按自定义事件键串行处理同键事件,适合保护会话状态流转。
func WithSerialByConversation ¶
func WithSerialByConversation() Option
WithSerialByConversation 让同一会话内的事件按顺序处理。
func WithSuperUsers ¶
WithSuperUsers 配置 App 级超级用户 ID,供 RequireSuperUser 和 Context.IsSuperUser 使用。
func WithWorkers ¶
WithWorkers 配置并发处理事件的 worker 数;不大于 0 时由适配器回调同步处理。
type PanicError ¶
PanicError 包装处理函数或中间件中恢复到的 panic 值和调用栈。
func (*PanicError) Error ¶
func (e *PanicError) Error() string
type ReplyTarget ¶
type ReplyTarget struct {
Protocol Protocol
SelfID string
UserID string
GroupID string
GuildID string
ChannelID string
EventID string
}
ReplyTarget 描述一次消息回复的自然目标。
type Route ¶
type Route struct {
// contains filtered or unexported fields
}
Route 表示一条可配置的事件路由。
type Router ¶
type Router struct {
// contains filtered or unexported fields
}
Router 组织路由、中间件和共享基础规则。
type Rule ¶
Rule 判断路由是否应处理当前事件。
func CommandWithPrefixes ¶
CommandWithPrefixes 使用显式前缀集合匹配命令,并写入 prefix、command、args 和 argv。
func Permission ¶ added in v1.2.0
Permission 匹配满足任一标准权限标识的事件。
func RegexpRule ¶
RegexpRule 使用已编译的正则表达式匹配事件文本,并写入 matches 与命名分组变量。
type Session ¶
type Session struct {
// contains filtered or unexported fields
}
Session 是基于固定键前缀的 Store 视图。
func NewUnavailableSession ¶
NewUnavailableSession 创建一个会在读写时返回 err 的会话视图。
type StatefulAdapter ¶
type StatefulAdapter interface {
State() AdapterState
SetStateSink(AdapterStateSink)
}
StatefulAdapter 是可向运行时暴露动作通道状态的适配器扩展接口。
type Store ¶
type Store interface {
Get(context.Context, string) ([]byte, bool, error)
Set(context.Context, string, []byte, time.Duration) error
Delete(context.Context, string) error
}
Store 定义会话数据的读写接口,值以字节形式存储并可带 TTL。