core

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

core 包提供机器人运行时、事件路由、中间件、会话存储、生命周期任务、 事件旁路观察、动作通道状态和协议适配核心。

core 是嵌入式程序和协议适配器使用的底层包。上层运行框架负责配置装配、 状态命名空间、持久化目录和运行编排。

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrPass 表示当前路由主动让出处理权,后续路由继续匹配。
	ErrPass = errors.New("anybot: pass route")
	// ErrStop 表示当前事件应停止向后续路由传播。
	ErrStop = errors.New("anybot: stop route")
	// ErrUnauthorized 表示当前事件没有通过权限检查。
	ErrUnauthorized = errors.New("anybot: unauthorized")
	// ErrRateLimited 表示当前限速窗口已被耗尽。
	ErrRateLimited = errors.New("anybot: rate limited")
	// ErrActionUnavailable 表示动作客户端当前暂不可用,通常是连接尚未建立或已临时断开。
	ErrActionUnavailable = errors.New("anybot: action unavailable")
	// ErrReplyTargetUnavailable 表示当前事件或目标无法映射到可回复的会话。
	ErrReplyTargetUnavailable = errors.New("anybot: reply target unavailable")
	// ErrSessionUnavailable 表示当前事件或运行时无法映射到请求的会话维度。
	ErrSessionUnavailable = errors.New("anybot: session unavailable")
)

Functions

func Configure

func Configure(opts ...Option)

Configure 将配置选项应用到默认 App。

func Every

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

Every 向默认 App 注册生命周期托管的周期任务。

func Go

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

Go 向默认 App 注册生命周期托管的后台任务。

func GoWhenActionReady

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

GoWhenActionReady 向默认 App 注册等待动作客户端可用后执行的生命周期任务。

func OnAdapterState

func OnAdapterState(hook AdapterStateHook)

OnAdapterState 向默认 App 注册适配器状态变化钩子。

func OnError

func OnError(handler ErrorHandler)

OnError 向默认 App 注册错误处理回调。

func OnObserverError

func OnObserverError(handler ObserverErrorHandler)

OnObserverError 向默认 App 注册观察者错误处理回调。

func OnReady

func OnReady(hook Hook)

OnReady 向默认 App 注册就绪钩子。

func OnShutdown

func OnShutdown(hook Hook)

OnShutdown 向默认 App 注册关闭钩子。

func OnStart

func OnStart(hook Hook)

OnStart 向默认 App 注册启动钩子。

func OnStop

func OnStop(hook Hook)

OnStop 是 OnShutdown 的兼容别名。

func ResetDefault

func ResetDefault(opts ...Option)

ResetDefault 使用新配置替换默认 App,主要用于测试和极小工具。

func Run

func Run(ctxs ...context.Context) error

Run 启动默认 App;未传 context 时使用 context.Background。

func Use

func Use(middleware ...Middleware)

Use 向默认 App 注册全局中间件。

func WaitActionReady

func WaitActionReady(ctx context.Context) error

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 最近一次已知的适配器状态。

func (AdapterState) Ready

func (s AdapterState) Ready() bool

Ready 判断动作客户端当前是否可用。

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 Default

func Default() *App

Default 返回快捷入口使用的进程级默认 App。

func New

func New(opts ...Option) *App

New 创建新的运行时实例,并应用传入的配置选项。

func (*App) Adapter

func (a *App) Adapter() Adapter

Adapter 返回当前运行时配置的协议适配器;未配置时返回 nil。

func (*App) AdapterState

func (a *App) AdapterState() AdapterState

AdapterState 返回最近一次已知的适配器状态。

func (*App) Client

func (a *App) Client() ActionClient

Client 返回适配器提供的动作客户端;运行时或适配器为空时返回 nil。

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) Every

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

Every 注册一个随 App 生命周期托管的周期任务。

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) Group

func (a *App) Group(rules ...Rule) *Router

Group 创建共享基础规则的路由组,便于把同类路由收束在一起。

func (*App) IsSuperUser

func (a *App) IsSuperUser(id any) bool

IsSuperUser 判断给定用户 ID 是否属于当前 App 的超级用户。

func (*App) Logger

func (a *App) Logger() *slog.Logger

Logger 返回运行时使用的日志器。

func (*App) Observe

func (a *App) Observe(rules ...Rule) *Observer

Observe 注册事件旁路观察者。观察者不会参与 route ordering、Stop 或 Pass。

func (*App) On

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

On 注册通用事件路由。

func (*App) OnAdapterState

func (a *App) OnAdapterState(hook AdapterStateHook)

OnAdapterState 注册适配器状态变化钩子。

func (*App) OnError

func (a *App) OnError(handler ErrorHandler)

OnError 注册路由处理错误的回调。

func (*App) OnMessage

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

OnMessage 注册消息事件路由,相当于在规则前追加 MessageEvent。

func (*App) OnObserverError

func (a *App) OnObserverError(handler ObserverErrorHandler)

OnObserverError 注册观察者错误处理器。

func (*App) OnReady

func (a *App) OnReady(hook Hook)

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

func (*App) OnShutdown

func (a *App) OnShutdown(hook Hook)

OnShutdown 注册关闭钩子,执行顺序与注册顺序相反。

func (*App) OnStart

func (a *App) OnStart(hook Hook)

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

func (*App) OnStop

func (a *App) OnStop(hook Hook)

OnStop 是 OnShutdown 的兼容别名。

func (*App) Regex

func (a *App) Regex(pattern string) *Route

Regex 注册文本正则路由,并把匹配结果写入 Context 的匹配变量。

func (*App) Router

func (a *App) Router() *Router

Router 返回根路由器,适合在需要细分路由组时使用。

func (*App) Run

func (a *App) Run(ctx context.Context) error

Run 启动生命周期钩子、适配器和事件调度器,并在 ctx 结束后退出。

func (*App) Store

func (a *App) Store() Store

Store 返回运行时使用的会话存储。

func (*App) SuperUsers

func (a *App) SuperUsers() []string

SuperUsers 返回当前 App 配置的超级用户 ID。

func (*App) Use

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

Use 注册全局中间件。全局中间件会包裹所有路由处理函数。

func (*App) WaitActionReady

func (a *App) WaitActionReady(ctx context.Context) error

WaitActionReady 阻塞直到动作客户端可用,或 ctx 结束。

type Context

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

Context 是路由处理函数的工作上下文,聚合事件、运行时能力、匹配结果和局部值。

func NewTestContext

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

NewTestContext 创建测试用上下文;app 为空时会使用默认配置的新 App。

func (*Context) Adapter

func (c *Context) Adapter() Adapter

Adapter 返回当前运行时配置的协议适配器。

func (*Context) App

func (c *Context) App() *App

App 返回当前上下文所属的运行时。

func (*Context) Args

func (c *Context) Args() string

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

func (*Context) Argv

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

Argv 返回按空白拆分后的命令参数,并保留简单引号与转义处理。

func (*Context) Client

func (c *Context) Client() ActionClient

Client 返回适配器动作客户端,可用于协议无关的消息发送。

func (*Context) Command

func (c *Context) Command() string

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

func (*Context) ConversationID

func (c *Context) ConversationID() string

ConversationID 返回当前事件对应的会话键,可直接用于会话存储。

func (*Context) Event

func (c *Context) Event() *Event

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

func (*Context) Get

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

Get 读取当前路由处理链内的局部值。

func (*Context) GroupID

func (c *Context) GroupID() string

GroupID 返回当前事件的群 ID,非群事件返回空字符串。

func (*Context) GroupRole added in v1.2.0

func (c *Context) GroupRole() string

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

func (*Context) GroupSession

func (c *Context) GroupSession() *Session

GroupSession 返回当前群或频道维度的存储视图。

func (*Context) HasAnyPermission added in v1.2.0

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

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

func (*Context) HasPermission added in v1.2.0

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

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

支持的基础标识包括 all、user、private、group、group.member、 group.manager、group.owner 与 superuser。group.manager 包含群主。

func (*Context) IsGroup

func (c *Context) IsGroup() bool

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

func (*Context) IsPrivate

func (c *Context) IsPrivate() bool

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

func (*Context) IsSuperUser

func (c *Context) IsSuperUser() bool

IsSuperUser 判断当前事件发送者是否属于当前 App 的超级用户。

func (*Context) Logger

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

Logger 返回运行时日志器;上下文未绑定运行时时返回 slog.Default。

func (*Context) Match

func (c *Context) Match() Match

Match 返回当前路由的匹配详情,包括评分、原因和规则写入的变量副本。

func (*Context) Pass

func (c *Context) Pass() error

Pass 跳过当前路由且不视为失败,后续路由仍会继续匹配。

func (*Context) RawEvent

func (c *Context) RawEvent() any

RawEvent 返回适配器保留的原始协议事件对象,便于在需要时访问协议专属字段。

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 使用事件的自然目标发送纯文本回复。

func (*Context) Route

func (c *Context) Route() *Route

Route 返回当前正在执行的路由。

func (*Context) RouteName

func (c *Context) RouteName() string

RouteName 返回当前路由的诊断名称,未命名时返回空字符串。

func (*Context) SelfID

func (c *Context) SelfID() string

SelfID 返回当前机器人账号 ID,事件为空时返回空字符串。

func (*Context) Session

func (c *Context) Session() *Session

Session 返回当前会话维度的存储视图。

func (*Context) SessionBy

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

SessionBy 返回指定键空间下的存储视图;key 为空时使用默认会话键。

func (*Context) Set

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

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

func (*Context) Stop

func (c *Context) Stop()

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

func (*Context) StopError

func (c *Context) StopError() error

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

func (*Context) Stopped

func (c *Context) Stopped() bool

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

func (*Context) Store

func (c *Context) Store() Store

Store 返回运行时配置的会话存储。

func (*Context) String

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

String 读取当前路由处理链内的字符串局部值;不存在或类型不匹配时返回空字符串。

func (*Context) Target

func (c *Context) Target() ReplyTarget

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

func (*Context) Text

func (c *Context) Text() string

Text 返回事件中的文本内容,优先使用标准化文本,再回退到消息链文本。

func (*Context) UserID

func (c *Context) UserID() string

UserID 返回当前事件的用户 ID,事件为空时返回空字符串。

func (*Context) UserSession

func (c *Context) UserSession() *Session

UserSession 返回当前用户维度的存储视图。

func (*Context) Var

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

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

func (*Context) VarString

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

VarString 读取当前规则匹配写入的字符串变量;不存在或类型不匹配时返回空字符串。

type EmitFunc

type EmitFunc func(context.Context, *Event) error

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

type ErrorHandler

type ErrorHandler func(*Context, error)

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

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) Clone

func (e *Event) Clone() *Event

Clone 返回事件副本,适合交给异步观察者或后台任务保存。

func (*Event) ConversationID

func (e *Event) ConversationID() string

ConversationID 返回适合会话存储的稳定键,优先按频道、群聊、私聊逐级区分。

func (*Event) DecodeRaw

func (e *Event) DecodeRaw(out any) error

DecodeRaw 将原始协议事件 JSON 解码到 out;没有原始数据时直接返回 nil。

func (*Event) GroupSessionID

func (e *Event) GroupSessionID() string

GroupSessionID 返回按群或频道维度隔离的存储键。

func (*Event) IsMessage

func (e *Event) IsMessage() bool

IsMessage 判断该事件是否为消息事件。

func (*Event) Target

func (e *Event) Target() ReplyTarget

Target 返回该事件的自然回复目标,供 Context.Reply 和适配器发送消息使用。

func (*Event) UserSessionID

func (e *Event) UserSessionID() string

UserSessionID 返回按用户维度隔离的存储键。

type EventKeyFunc

type EventKeyFunc func(*Event) string

EventKeyFunc 返回事件串行调度使用的键;空键表示不参与串行化。

type FileStore

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

FileStore 是 goroutine 安全的文件持久化 Store,适合保存轻量会话状态。

func NewFileStore

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

NewFileStore 打开或创建一个 JSON 文件存储。文件不存在时会在第一次写入时创建。

func (*FileStore) Delete

func (s *FileStore) Delete(ctx context.Context, key string) error

Delete 删除指定键。

func (*FileStore) Get

func (s *FileStore) Get(ctx context.Context, key string) ([]byte, bool, error)

Get 读取指定键的值;键不存在或已过期时返回 ok=false。

func (*FileStore) Path

func (s *FileStore) Path() string

Path 返回当前存储文件路径。

func (*FileStore) Set

func (s *FileStore) Set(ctx context.Context, key string, value []byte, ttl time.Duration) error

Set 写入指定键的值。ttl 大于 0 时,值会在到期后失效。

func (*FileStore) Sweep

func (s *FileStore) Sweep(ctx context.Context) error

Sweep 立即清理所有已过期的文件存储项。

type Handler

type Handler func(*Context) error

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

type Hook

type Hook func(context.Context) error

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

type Match

type Match struct {
	Score  float64
	Reason string
	Vars   map[string]any
}

Match 描述规则匹配结果,包含评分、诊断原因和传递给处理函数的变量。

func (Match) WithVar

func (m Match) WithVar(key string, value any) Match

WithVar 向匹配结果追加变量,并返回更新后的 Match。

type MemoryStore

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

MemoryStore 是 goroutine 安全的进程内 Store,适合短期会话状态。

func NewMemoryStore

func NewMemoryStore() *MemoryStore

NewMemoryStore 创建默认内存存储。

func (*MemoryStore) Delete

func (s *MemoryStore) Delete(ctx context.Context, key string) error

Delete 删除指定键。

func (*MemoryStore) Get

func (s *MemoryStore) Get(ctx context.Context, key string) ([]byte, bool, error)

Get 读取指定键的值;键不存在或已过期时返回 ok=false。

func (*MemoryStore) Set

func (s *MemoryStore) Set(ctx context.Context, key string, value []byte, ttl time.Duration) error

Set 写入指定键的值。ttl 大于 0 时,值会在到期后失效。

func (*MemoryStore) Sweep

func (s *MemoryStore) Sweep(ctx context.Context) error

Sweep 立即清理所有已过期的内存项。

type MessageReceipt

type MessageReceipt struct {
	ID string
}

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(*Context) string) Middleware

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 时不生效。

func Trace

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

Trace 在每次路由处理结束后记录耗时、路由名称和事件关键信息。

type Observer

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

Observer 表示一条事件旁路观察规则。

func Observe

func Observe(rules ...Rule) *Observer

Observe 向默认 App 注册事件旁路观察者。

func (*Observer) Handle

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

Handle 设置观察者处理函数。

func (*Observer) Name

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

Name 设置观察者名称,便于日志诊断。

type ObserverErrorHandler

type ObserverErrorHandler func(context.Context, *Event, error)

ObserverErrorHandler 处理事件观察者返回的错误或 panic。

type ObserverHandler

type ObserverHandler func(context.Context, *Event) error

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

type Option

type Option func(*App)

Option 调整 App 的运行时配置。

func WithAdapter

func WithAdapter(adapter Adapter) Option

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

func WithBuffer

func WithBuffer(size int) Option

WithBuffer 配置事件队列大小;不大于 0 的值会被忽略。

func WithErrorHandler

func WithErrorHandler(handler ErrorHandler) Option

WithErrorHandler 注册错误处理器。

func WithLogger

func WithLogger(logger *slog.Logger) Option

WithLogger 配置运行时日志器;nil 会被忽略。

func WithObserverBuffer

func WithObserverBuffer(size int) Option

WithObserverBuffer 配置异步事件观察者的并发队列容量;不大于 0 的值会被忽略。

func WithSerialBy

func WithSerialBy(fn EventKeyFunc) Option

WithSerialBy 按自定义事件键串行处理同键事件,适合保护会话状态流转。

func WithSerialByConversation

func WithSerialByConversation() Option

WithSerialByConversation 让同一会话内的事件按顺序处理。

func WithStore

func WithStore(store Store) Option

WithStore 配置会话存储;nil 会被忽略。

func WithSuperUsers

func WithSuperUsers(ids ...string) Option

WithSuperUsers 配置 App 级超级用户 ID,供 RequireSuperUser 和 Context.IsSuperUser 使用。

func WithWorkers

func WithWorkers(workers int) Option

WithWorkers 配置并发处理事件的 worker 数;不大于 0 时由适配器回调同步处理。

type PanicError

type PanicError struct {
	Value any
	Stack []byte
}

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

func (*PanicError) Error

func (e *PanicError) Error() string

type Protocol

type Protocol string

Protocol 标识事件和动作所属的协议,具体取值由适配器包定义。

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 表示一条可配置的事件路由。

func Command

func Command(names ...string) *Route

Command 向默认 App 注册命令路由。

func On

func On(rules ...Rule) *Route

On 向默认 App 注册通用事件路由。

func OnMessage

func OnMessage(rules ...Rule) *Route

OnMessage 向默认 App 注册消息事件路由。

func Regex

func Regex(pattern string) *Route

Regex 向默认 App 注册文本正则路由。

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 Router

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

Router 组织路由、中间件和共享基础规则。

func (*Router) Command

func (r *Router) Command(names ...string) *Route

Command 注册命令路由,默认识别 /、!、. 三种前缀。

func (*Router) Group

func (r *Router) Group(rules ...Rule) *Router

Group 创建继承当前基础规则的子路由器。

func (*Router) On

func (r *Router) On(rules ...Rule) *Route

On 注册一条通用事件路由。

func (*Router) OnMessage

func (r *Router) OnMessage(rules ...Rule) *Route

OnMessage 注册消息事件路由。

func (*Router) Regex

func (r *Router) Regex(pattern string) *Route

Regex 注册文本正则路由。

func (*Router) Use

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

Use 追加路由器中间件。根路由器上的中间件作用于所有路由。

type Rule

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

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

func All

func All(rules ...Rule) Rule

All 要求传入的所有规则都匹配,并合并它们的匹配结果。

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 使用显式前缀集合匹配命令,并写入 prefix、command、args 和 argv。

func Contains

func Contains(substr string) Rule

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

func DetailType

func DetailType(kind string) Rule

DetailType 匹配标准化事件细分类型,例如 group、private 或心跳事件。

func EventType

func EventType(kind string) Rule

EventType 匹配标准化事件类型,例如 message、notice 或 request。

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 匹配指定文本前缀,并把剩余文本写入 rest 变量。

func Private

func Private() Rule

Private 匹配私聊消息。

func RegexRule

func RegexRule(pattern string) Rule

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

func RegexpRule

func RegexpRule(re *regexp.Regexp) Rule

RegexpRule 使用已编译的正则表达式匹配事件文本,并写入 matches 与命名分组变量。

func ToMe

func ToMe() Rule

ToMe 匹配私聊消息,或群聊中提及当前机器人的消息。

type RuleFunc

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

RuleFunc 将普通函数适配为 Rule。

func (RuleFunc) Match

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

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

type Session

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

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

func NewSession

func NewSession(store Store, key string) *Session

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

func NewUnavailableSession

func NewUnavailableSession(err error) *Session

NewUnavailableSession 创建一个会在读写时返回 err 的会话视图。

func (*Session) Delete

func (s *Session) Delete(ctx context.Context, name string) error

Delete 删除会话视图中的值。

func (*Session) Get

func (s *Session) Get(ctx context.Context, name string) ([]byte, bool, error)

Get 读取会话视图中的原始字节值。

func (*Session) Key

func (s *Session) Key() string

Key 返回当前会话视图使用的键前缀。

func (*Session) LoadJSON

func (s *Session) LoadJSON(ctx context.Context, name string, out any) (bool, error)

LoadJSON 读取会话值并按 JSON 解码到 out。

func (*Session) SaveJSON

func (s *Session) SaveJSON(ctx context.Context, name string, value any, ttl time.Duration) error

SaveJSON 将 value 编码为 JSON 后写入会话视图。

func (*Session) Set

func (s *Session) Set(ctx context.Context, name string, value []byte, ttl time.Duration) error

Set 写入会话视图中的原始字节值。

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。

type TaskFunc

type TaskFunc func(context.Context) error

TaskFunc 是由 App 生命周期托管的后台任务函数。

type TaskOption

type TaskOption func(*taskOptions)

TaskOption 调整后台任务行为。

func TaskCritical

func TaskCritical() TaskOption

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

func TaskImmediate

func TaskImmediate() TaskOption

TaskImmediate 让周期任务在启动后立即执行一次,然后再按间隔执行。

Directories

Path Synopsis
message 包定义 AnyBot 的协议中立消息链。
message 包定义 AnyBot 的协议中立消息链。

Jump to

Keyboard shortcuts

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