Documentation
¶
Overview ¶
Package remilia 是对核心引擎的高级封装,提供完整的生命周期管理。
Remilia 受 wdvxdr1123/ZeroBot 架构启发,但为完全独立的实现。 本项目不包含 ZeroBot 的任何受版权保护的代码。 ZeroBot 是 GPL-3.0 许可的开源项目:https://github.com/wdvxdr1123/ZeroBot
Bot 是使用 Remilia 框架构建事件驱动应用的主入口,提供:
- 生命周期管理(启动/停止)
- 健康检查
- 配置管理
- 通过 platform.Adapter 处理多平台事件
平台无关用法(推荐) ¶
使用平台无关的事件匹配注册处理器:
import (
"context"
"log"
"github.com/KomeiDiSanXian/remilia"
"github.com/KomeiDiSanXian/remilia/core/engine"
eventctx "github.com/KomeiDiSanXian/remilia/core/context"
"github.com/KomeiDiSanXian/remilia/platform"
)
eng := engine.NewEngine()
// 注册一个适用于任意平台的命令处理器。
// Reply 是异步发送(返回 Future),忽略返回值即"发出即忘"。
eng.OnCommand("", "/hello").
Handle(func(ctx *eventctx.Context) error {
ctx.Reply(platform.TextMessage("Hello!"))
return nil
})
// 通过 platform.Adapter 构建 Bot
bot, err := remilia.NewBotBuilder().
WithPlatformAdapter(qqAdapter). // platform.Adapter
WithEngine(eng).
Build()
QQ 用法 ¶
对于 QQ 机器人,使用 Bot 凭证创建 [qq.WebhookServerAdapter] 并传入构建器。 适配器内部自动管理 Token 刷新和消息发送:
import "github.com/KomeiDiSanXian/remilia/platform/qq"
import "github.com/KomeiDiSanXian/remilia/platform/qq/openapi/dto"
botInfo := &dto.BotInfo{
AppID: 123456,
Token: "your-token",
AppSecret: "your-secret",
}
adapter := qq.NewWebhookServerAdapter(":8080", botInfo)
bot, err := remilia.NewBotBuilder().
WithPlatformAdapter(adapter).
WithEngine(eng).
Build()
// 平台无关匹配器(推荐用于所有平台)
eng.OnEventKind(platform.EventKindPrivateMessage, eventctx.OnCommand("/ping")).Handle(pingHandler)
eng.OnEventKind(platform.EventKindGroupMessage, eventctx.OnCommand("/hello")).Handle(helloHandler)
多平台 ¶
通过 platform.Registry 将多个平台接入同一个 Bot 实例。 每次调用 BotBuilder.WithPlatformAdapter 会覆盖前一个适配器; 若需注册多个平台,请使用 BotBuilder.WithPlatformRegistry:
registry := platform.NewRegistry()
registry.Register(qqAdapter) // platform.PlatformAdapter
registry.Register(discordAdapter)
bot, err := remilia.NewBotBuilder().
WithPlatformRegistry(registry).
WithEngine(eng).
Build()
适配器接口 ¶
支持一种适配器接口:
- platform.Adapter(推荐):平台无关,处理器接收 platform.Event
健康检查 ¶
status := bot.Health()
fmt.Printf("Status: %s, Uptime: %v\n", status.Status, status.Uptime)
生命周期 ¶
Bot 使用 lifecycle 包:组件按顺序启动,按逆序停止。 启动失败会触发自动回滚。
Index ¶
- Constants
- func CaptureTrace(ctx context.Context, duration time.Duration, filename string) error
- type AdapterHealthChecker
- type Bot
- func (b *Bot) Config() BotMeta
- func (b *Bot) Context() context.Context
- func (b *Bot) Engine() *engine.Engine
- func (b *Bot) Health() health.CheckResponse
- func (b *Bot) HealthCheck() *health.Check
- func (b *Bot) IsRunning() bool
- func (b *Bot) OnAny(rule ...eventctx.Rule) *engine.Matcher
- func (b *Bot) OnEventKind(kind platform.EventKind, rule ...eventctx.Rule) *engine.Matcher
- func (b *Bot) PlatformRegistry() *platform.Registry
- func (b *Bot) Plugins() *plugin.Manager
- func (b *Bot) Restart() error
- func (b *Bot) Shutdown() error
- func (b *Bot) ShutdownAsync() <-chan error
- func (b *Bot) Start() error
- func (b *Bot) State() lifecycle.State
- func (b *Bot) Stop(ctx context.Context) error
- func (b *Bot) SyncPlatforms(desired map[string]platform.Adapter) error
- func (b *Bot) Uptime() time.Duration
- func (b *Bot) UsePlatformRegistry(r *platform.Registry) *Bot
- func (b *Bot) UsePlugins(pm *plugin.Manager) *Bot
- func (b *Bot) UseRouter(r *router.Router) *Bot
- func (b *Bot) WaitForShutdown(timeout ...time.Duration)
- type BotBuilder
- func (b *BotBuilder) Build() (*Bot, error)
- func (b *BotBuilder) MustBuild() *Bot
- func (b *BotBuilder) WithDebug(debug bool) *BotBuilder
- func (b *BotBuilder) WithEngine(eng *engine.Engine) *BotBuilder
- func (b *BotBuilder) WithEngineOptions(opts ...engine.Option) *BotBuilder
- func (b *BotBuilder) WithName(name string) *BotBuilder
- func (b *BotBuilder) WithOption(opt Option) *BotBuilder
- func (b *BotBuilder) WithPlatformAdapter(adapter platform.Adapter) *BotBuilder
- func (b *BotBuilder) WithPlatformRegistry(r *platform.Registry) *BotBuilder
- func (b *BotBuilder) WithPluginManager(pm *plugin.Manager) *BotBuilder
- func (b *BotBuilder) WithPlugins(descriptors ...*plugin.Descriptor) *BotBuilder
- func (b *BotBuilder) WithVersion(version string) *BotBuilder
- type BotError
- type BotHealthResult
- type BotManager
- func (m *BotManager) Add(name string, bot *Bot) error
- func (m *BotManager) Get(name string) (*Bot, bool)
- func (m *BotManager) HealthAll() map[string]BotHealthResult
- func (m *BotManager) Len() int
- func (m *BotManager) MustAdd(name string, bot *Bot) *BotManager
- func (m *BotManager) MustGet(name string) *Bot
- func (m *BotManager) Names() []string
- func (m *BotManager) Remove(name string) bool
- func (m *BotManager) RunningBots() []string
- func (m *BotManager) Shutdown() error
- func (m *BotManager) ShutdownAsync() <-chan error
- func (m *BotManager) StartAll() error
- func (m *BotManager) Status() BotManagerStatus
- func (m *BotManager) StopAll(ctx context.Context) error
- func (m *BotManager) WaitForShutdown(timeout ...time.Duration)
- type BotManagerBuilder
- type BotManagerError
- type BotManagerStatus
- type BotMeta
- type BotStatusChecker
- type DLQHealthAdapter
- type Option
- func WithAdapter(adapter platform.Adapter) Option
- func WithConfig(config *BotMeta) Option
- func WithDebug(debug bool) Option
- func WithEngine(engine *engine.Engine) Option
- func WithGoroutineThreshold(n int) Option
- func WithName(name string) Option
- func WithPprof(cfg PprofConfig) Option
- func WithVersion(version string) Option
- type PprofConfig
- type PprofServer
Constants ¶
const ( DefaultShutdownTimeout = 30 * time.Second DefaultStartTimeout = 30 * time.Second )
const Version = "1.24.0"
Version 是 Remilia 框架的当前版本号。 此文件是版本号的唯一来源。 如需更新版本,仅修改此常量即可。
Variables ¶
This section is empty.
Functions ¶
Types ¶
type AdapterHealthChecker ¶
type AdapterHealthChecker struct {
// contains filtered or unexported fields
}
AdapterHealthChecker 检查 Adapter 运行状态
func NewAdapterHealthChecker ¶
func NewAdapterHealthChecker(adapter platform.Adapter) *AdapterHealthChecker
NewAdapterHealthChecker 创建 Adapter 健康检查器
func (*AdapterHealthChecker) Check ¶
func (c *AdapterHealthChecker) Check(_ context.Context) health.CheckResult
Check 执行健康检查,通过 IsRunning() 判断适配器实际运行状态
type Bot ¶
type Bot struct {
// contains filtered or unexported fields
}
Bot 是对 Engine 的高级封装,提供完整的生命周期管理。
生命周期完全委托给 lifecycle.Manager,Bot 只存储配置和组件引用。 Bot.Start() 创建最外层 context 并交给 lifecycle,Bot.Stop() 委托给 lifecycle.Stop()。 lifecycle 管理双层 context:parentCtx(bot 根)→ runCtx(组件运行时)。
D3:Bot 内部统一使用 platformRegistry 作为唯一的平台适配器来源, 不再维护单独的 adapter 字段,消除双路径冗余逻辑。
func MustNewBot ¶
MustNewBot 同 NewBot,但失败时 panic。适用于初始化阶段且参数已确认合法的场景。
func NewBot ¶
NewBot 创建新的 Bot 实例。
adapter 可以为 nil(仅使用多平台注册表时),非 nil 时会自动包装进内部 Registry。 推荐使用 BotBuilder.Build() 代替直接调用。
若 engine 为 nil,返回错误。编写测试或确信参数合法时可使用 MustNewBot。
func (*Bot) Context ¶
Context 返回 Bot 的根 context。
等价于 lifecycle.ParentContext(),是 Bot 生命周期的最外层 context:
- Start() 期间创建,Stop() 中 OnStop 全部完成后取消
- 可用于创建与 Bot 生命周期绑定的后台 goroutine、初始化 AdaptiveRateLimiter 等
Start() 之前调用返回 context.Background()。
func (*Bot) Engine ¶
Engine 返回 Bot 的 Engine 实例
无需加锁:b.engine 在 NewBot 中设置一次且永不修改。 与 Config()/Plugins() 不同,这些字段通过 Use* 方法支持运行时注入。
func (*Bot) OnEventKind ¶
OnEventKind 注册处理指定平台事件类别的规则(平台无关,推荐)
func (*Bot) PlatformRegistry ¶
PlatformRegistry 返回已注入的多平台注册表,未注入时返回 nil
func (*Bot) ShutdownAsync ¶
ShutdownAsync 在后台 goroutine 中发起优雅关闭,立即返回。
返回一个只读 channel,关闭完成后会写入最终错误(nil 表示成功)。 调用方可选择是否等待结果:
// 触发后不等待(fire-and-forget)
bot.ShutdownAsync()
// 触发后等待结果
if err := <-bot.ShutdownAsync(); err != nil {
log.Println("shutdown error:", err)
}
适用于以下场景:
- HTTP handler 需要先响应客户端再关闭(同步 Shutdown 会阻塞响应)
- 插件回调内部触发关闭(同步调用会在 lifecycle 链上死锁)
- 与外部框架集成时,对方不允许阻塞其事件循环
注意:多次调用是安全的,后续调用会直接返回已关闭的 channel(Bot.Stop 本身幂等)。
func (*Bot) Start ¶
Start 启动 Bot。
生命周期由 lifecycle.Manager 管理,Bot 只负责:
- 构建 adapter snapshot 和注册 lifecycle 组件
- 创建最外层 context(作为 lifecycle.Start 的入参——lifecycle 内部剥离超时后存储为 parentCtx)
- 委托 lifecycle.Start
func (*Bot) Stop ¶
Stop 优雅停止 Bot。
生命周期完全委托给 lifecycle.Stop(),其内部顺序为:
- 取消 runCtx → 通知所有 OnRun goroutine 退出
- 逆序调用各组件的 OnStop: a. plugin-manager → 所有插件 Teardown(parentCtx 仍有效,可访问平台 API) b. platform adapters → 平台连接断开 c. engine shutdown
- 取消 parentCtx(Bot 根 context)
注意:已注册为 lifecycle.Component 的组件(含 pluginManager)由 lifecycle 自动管理, 无需手动调用 pm.StopAll()。
func (*Bot) SyncPlatforms ¶ added in v1.15.0
SyncPlatforms 热同步平台适配器集合:增、删、改均能处理。
desired 以 platform.Platform() 为 key,框架据此比对当前注册表中的适配器:
- 仅在 desired 中的 → 注册并启动
- 仅在当前注册表中的 → 停止并移除
- 两者都有的 → 用新的替换旧的(Stop + Start)
SyncPlatforms 启动的适配器运行在独立的 goroutine 中,由 bot.Context() 管理生命周期。 Bot.Stop() 会自动关闭所有通过 SyncPlatforms 启动的适配器。 调用方(cmd/bot)负责从 config 中创建 desired 适配器实例。
func (*Bot) WaitForShutdown ¶
WaitForShutdown 等待系统信号并优雅关闭。
收到第一个 SIGINT(Ctrl+C)或 SIGTERM 时,开始优雅关闭(等待后台清理完成)。 若在优雅关闭期间再次收到 SIGINT,立即强制退出(os.Exit(1)), 不再等待剩余清理工作——这与大多数 CLI 工具的行为一致。
timeout 为可选参数,指定优雅关闭的超时时间;省略时使用 DefaultShutdownTimeout(30s)。 若同一进程已有另一个 WaitForShutdown 处于监听状态,此次调用会直接返回并打印 Warn 日志。
若需要完全自定义 context(如携带 trace),请直接调用 Bot.Stop。
多 Bot 场景请统一使用 BotManager.WaitForShutdown。
type BotBuilder ¶
type BotBuilder struct {
// contains filtered or unexported fields
}
BotBuilder 提供流畅的Bot构建接口。
平台无关:不直接依赖任何具体平台(QQ、Discord 等)。 平台适配器由调用方创建后通过 BotBuilder.WithPlatformAdapter 或 BotBuilder.WithPlatformRegistry 注入,适配器自行管理其认证和发送逻辑。
使用示例(QQ Webhook):
adapter := qq.NewWebhookServerAdapter(":8080", botInfo)
bot, err := remilia.NewBotBuilder().
WithPlatformAdapter(adapter).
WithPlugins(plugin1.New(), plugin2.New()).
Build()
func (*BotBuilder) Build ¶
func (b *BotBuilder) Build() (*Bot, error)
Build 构建Bot实例。
D3:内部统一使用 registry 模式。若只设置了单个适配器(WithPlatformAdapter), Build() 会自动将其注册到 Registry 中,两种使用方式完全透明。
func (*BotBuilder) MustBuild ¶
func (b *BotBuilder) MustBuild() *Bot
MustBuild 构建Bot,如果失败则panic。 适用于确信配置正确的场景,简化错误处理。
func (*BotBuilder) WithDebug ¶
func (b *BotBuilder) WithDebug(debug bool) *BotBuilder
WithDebug 启用调试模式
func (*BotBuilder) WithEngine ¶
func (b *BotBuilder) WithEngine(eng *engine.Engine) *BotBuilder
WithEngine 设置自定义Engine
传入 nil 会被忽略并触发 warning,Build() 将创建默认 Engine。
func (*BotBuilder) WithEngineOptions ¶
func (b *BotBuilder) WithEngineOptions(opts ...engine.Option) *BotBuilder
WithEngineOptions 传递 engine.Option 给 Build() 内部创建的 Engine。
这允许在不绕过 BotBuilder 的情况下自定义 Engine 行为,例如调整清理间隔:
bot, err := remilia.NewBotBuilder().
WithPlatformAdapter(adapter).
WithEngineOptions(engine.WithCleanupInterval(10 * time.Minute)).
Build()
注意:若已通过 BotBuilder.WithEngine 传入外部 Engine 实例, 此方法设置的选项将被忽略(外部实例已完成初始化)。
func (*BotBuilder) WithName ¶
func (b *BotBuilder) WithName(name string) *BotBuilder
WithName 设置Bot名称
func (*BotBuilder) WithOption ¶
func (b *BotBuilder) WithOption(opt Option) *BotBuilder
WithOption 添加自定义选项
func (*BotBuilder) WithPlatformAdapter ¶
func (b *BotBuilder) WithPlatformAdapter(adapter platform.Adapter) *BotBuilder
WithPlatformAdapter 设置单平台适配器。
每次调用会覆盖上一次设置的适配器;若需要同时运行多个平台, 请改用 BotBuilder.WithPlatformRegistry。
func (*BotBuilder) WithPlatformRegistry ¶
func (b *BotBuilder) WithPlatformRegistry(r *platform.Registry) *BotBuilder
WithPlatformRegistry 注入多平台适配器注册表。
若此前已通过 WithPlatformAdapter 注册了单个适配器,此方法会先将其迁移到新注册表中, 避免覆盖丢失。也支持多次调用——后调用的注册表会继承前一个的所有适配器:
// 方式一:仅注册表
bot, err := remilia.NewBotBuilder().
WithPlatformRegistry(platform.NewRegistry().Register(qqAdapter)).
Build()
// 方式二:单适配器扩充为注册表(自动合并)
bot, err := remilia.NewBotBuilder().
WithPlatformAdapter(discordAdapter).
WithPlatformRegistry(registry.WithAdapter(qqAdapter)). // registry 继承 discord
Build()
func (*BotBuilder) WithPluginManager ¶
func (b *BotBuilder) WithPluginManager(pm *plugin.Manager) *BotBuilder
WithPluginManager 注入插件管理器,将其生命周期与 Bot 绑定。
Build() 后,Bot.Start() 会自动触发所有插件的 Setup, Bot.Stop() 会自动按逆序触发所有插件的 Teardown。
注意:WithPluginManager 与 WithPlugins 可同时使用; WithPlugins 注册的描述符会追加到此 Manager 中。
func (*BotBuilder) WithPlugins ¶
func (b *BotBuilder) WithPlugins(descriptors ...*plugin.Descriptor) *BotBuilder
WithPlugins 一步注册多个插件描述符,无需手动创建 plugin.Manager。
Build() 阶段自动创建(或复用已有的)plugin.Manager 并批量注册, 注册顺序自动按依赖拓扑排序(等同于 RegisterMultipleSmart)。
这是框架推荐的最简洁插件集成方式:
adapter := qq.NewWebhookServerAdapter(":8080", botInfo)
bot, err := remilia.NewBotBuilder().
WithPlatformAdapter(adapter).
WithPlugins(myPlugin.New(), anotherPlugin.New()).
Build()
func (*BotBuilder) WithVersion ¶
func (b *BotBuilder) WithVersion(version string) *BotBuilder
WithVersion 设置Bot版本
type BotError ¶
BotError 代表 BotManager 中单个 Bot 的操作失败。
通过 errors.Is / errors.As 可以检查具体哪个 Bot 失败了:
var be remilia.BotError
if errors.As(err, &be) {
log.Printf("bot %s failed: %v", be.Name, be.Err)
}
type BotHealthResult ¶
type BotHealthResult struct {
Name string
IsRunning bool
Health health.CheckResponse
}
BotHealthResult 包含单个 Bot 的名称、运行状态和健康检查结果。
type BotManager ¶
type BotManager struct {
// contains filtered or unexported fields
}
BotManager 管理多个 Bot 实例的生命周期。
每个 Bot 独立持有自己的 Engine、Adapter 和 lifecycle, BotManager 仅负责统一的启停调度和命名查找。
典型使用场景:
- 同一进程运行多个 QQ Bot 账号(测试账号 + 生产账号)
- 同一逻辑服务的多个机器人实例(分担消息负载)
- 灰度发布:旧 Bot 继续运行,新 Bot 逐步接入
示例:
mgr := remilia.NewBotManager()
mgr.Add("prod", prodBot)
mgr.Add("test", testBot)
if err := mgr.StartAll(ctx); err != nil {
log.Fatal(err)
}
mgr.WaitForShutdown()
func (*BotManager) Add ¶
func (m *BotManager) Add(name string, bot *Bot) error
Add 注册一个命名 Bot 实例。 若同名 Bot 已存在,返回错误;若 bot 为 nil,同样返回错误。
func (*BotManager) Get ¶
func (m *BotManager) Get(name string) (*Bot, bool)
Get 按名称获取 Bot 实例。若不存在,返回 nil, false。
func (*BotManager) HealthAll ¶
func (m *BotManager) HealthAll() map[string]BotHealthResult
HealthAll 并发执行所有 Bot 的健康检查,以 map[name]CheckResponse 返回。
func (*BotManager) MustAdd ¶
func (m *BotManager) MustAdd(name string, bot *Bot) *BotManager
MustAdd 注册 Bot,失败时 panic。
此方法仅适用于程序 main() 初始化阶段,在配置已确认正确的前提下使用, 目的是减少样板错误处理代码。
警告:请勿在运行时(如插件回调、HTTP handler、goroutine 中)调用此方法, 否则 panic 将导致整个进程崩溃。运行时场景请使用 BotManager.Add。
func (*BotManager) MustGet ¶
func (m *BotManager) MustGet(name string) *Bot
MustGet 按名称获取 Bot 实例,若不存在则 panic。
此方法仅适用于程序 main() 初始化阶段,在确信目标 Bot 已通过 Add/MustAdd 注册的前提下使用。
警告:请勿在运行时(如插件回调、HTTP handler、goroutine 中)调用此方法, 否则 panic 将导致整个进程崩溃。运行时场景请使用 BotManager.Get。
func (*BotManager) Remove ¶
func (m *BotManager) Remove(name string) bool
Remove 从管理器中移除 Bot。 注意:Remove 不会自动停止 Bot,请在 Remove 前先调用 bot.Stop()。
func (*BotManager) RunningBots ¶
func (m *BotManager) RunningBots() []string
RunningBots 返回当前处于运行状态的 Bot 名称列表。
func (*BotManager) Shutdown ¶
func (m *BotManager) Shutdown() error
Shutdown 使用默认超时时间停止所有 Bot(DefaultShutdownTimeout)。
func (*BotManager) ShutdownAsync ¶
func (m *BotManager) ShutdownAsync() <-chan error
ShutdownAsync 在后台 goroutine 中发起优雅关闭,立即返回。
返回一个只读 channel,所有 Bot 关闭完成后会写入最终错误(nil 表示全部成功)。 调用方可选择是否等待结果:
// 触发后不等待(fire-and-forget)
mgr.ShutdownAsync()
// 触发后等待结果
if err := <-mgr.ShutdownAsync(); err != nil {
log.Println("shutdown error:", err)
}
适用于以下场景:
- HTTP handler 收到 /shutdown 请求,需先响应 200 再后台关闭
- 插件回调内部触发关闭(同步调用会在 lifecycle 链上死锁)
- 与外部框架集成时对方不允许阻塞其事件循环
注意:多次调用是安全的,StopAll 对每个 Bot 的 Stop 调用均幂等。
func (*BotManager) StartAll ¶
func (m *BotManager) StartAll() error
StartAll 并发启动所有已注册的 Bot。 任何一个 Bot 启动失败都会记录错误,但不会阻止其他 Bot 的启动。 若所有 Bot 均启动失败,返回聚合错误;若部分失败,同样返回聚合错误, 调用方可通过 errors.Is / errors.As 检查具体失败项。
func (*BotManager) StopAll ¶
func (m *BotManager) StopAll(ctx context.Context) error
StopAll 并发停止所有正在运行的 Bot,使用给定的 context 作为超时控制。 即使部分 Bot 停止失败,也会继续停止其他 Bot,最终返回聚合错误(如有)。
func (*BotManager) WaitForShutdown ¶
func (m *BotManager) WaitForShutdown(timeout ...time.Duration)
WaitForShutdown 阻塞直到收到 SIGINT/SIGTERM 信号,然后优雅停止所有 Bot。 这是生产环境启动多 Bot 后的标准收尾调用。
收到第一个 SIGINT(Ctrl+C)或 SIGTERM 时,开始优雅关闭(等待后台清理完成)。 若在优雅关闭期间再次收到 SIGINT,立即强制退出(os.Exit(1)), 不再等待剩余清理工作——这与大多数 CLI 工具的行为一致。
timeout 为可选参数,指定优雅关闭的超时时间;省略时使用 DefaultShutdownTimeout(30s)。 若同一进程已有另一个 WaitForShutdown 处于监听状态,此次调用会直接返回并打印 Warn 日志。
若需要完全自定义 context(如携带 trace),请直接调用 BotManager.StopAll。
示例:
mgr.StartAll() mgr.WaitForShutdown() // 使用默认 30s 超时 mgr.WaitForShutdown(60 * time.Second) // 自定义超时
type BotManagerBuilder ¶
type BotManagerBuilder struct {
// contains filtered or unexported fields
}
BotManagerBuilder 提供流畅的 BotManager 构建接口。
示例:
mgr, err := remilia.NewBotManagerBuilder().
Add("prod", prodAdapter, &prodBotInfo).
Add("test", testAdapter, &testBotInfo).
Build()
func NewBotManagerBuilder ¶
func NewBotManagerBuilder() *BotManagerBuilder
NewBotManagerBuilder 创建 BotManager 构建器。
func (*BotManagerBuilder) AddBot ¶
func (b *BotManagerBuilder) AddBot(name string, bot *Bot) *BotManagerBuilder
AddBot 向构建器中添加一个已构建的 Bot 实例。
func (*BotManagerBuilder) AddBuilder ¶
func (b *BotManagerBuilder) AddBuilder(name string, builder *BotBuilder) *BotManagerBuilder
AddBuilder 向构建器中添加一个 BotBuilder,Build() 时自动构建。 这允许延迟构建,统一处理错误。
func (*BotManagerBuilder) Build ¶
func (b *BotManagerBuilder) Build() (*BotManager, error)
Build 构建 BotManager,返回错误(如有)。
func (*BotManagerBuilder) MustBuild ¶
func (b *BotManagerBuilder) MustBuild() *BotManager
MustBuild 构建 BotManager,失败时 panic。
type BotManagerError ¶
BotManagerError 代表 BotManager 批量操作(StartAll / StopAll)中的聚合错误。
通过 BotManagerError.FailedBots() 可获取所有失败 Bot 的名称列表。 支持 errors.Is / errors.As 提取具体 Bot 的错误。
func (*BotManagerError) Error ¶
func (e *BotManagerError) Error() string
func (*BotManagerError) FailedBots ¶
func (e *BotManagerError) FailedBots() []string
FailedBots 返回所有失败的 Bot 名称列表
type BotManagerStatus ¶
BotManagerStatus 描述 BotManager 当前整体状态
type BotStatusChecker ¶
type BotStatusChecker struct {
// contains filtered or unexported fields
}
BotStatusChecker 检查 Bot 的基本状态
func NewBotStatusChecker ¶
func NewBotStatusChecker(bot *Bot) *BotStatusChecker
NewBotStatusChecker 创建 Bot 状态检查器
func (*BotStatusChecker) Check ¶
func (c *BotStatusChecker) Check(_ context.Context) health.CheckResult
Check 执行健康检查
type DLQHealthAdapter ¶
type DLQHealthAdapter struct {
// contains filtered or unexported fields
}
DLQHealthAdapter 将任意 dlq.Queue[T] 适配为 health.DLQStats 接口。
这是解决 infra/health 不应直接依赖 infra/dlq 的适配器(Adapter Pattern)。 infra/health 只知道 health.DLQStats 接口,实际的 DLQ 类型在上层(bot 层)注入。
使用示例:
q := dlq.NewPayloadQueue(dlq.PayloadConfig{...})
adapter := remilia.NewDLQHealthAdapter(q)
botHealth.AddChecker(health.NewDeadLetterQueueHealthChecker(adapter, 1000, 0.1))
func NewDLQHealthAdapter ¶
func NewDLQHealthAdapter(q dlqStater) *DLQHealthAdapter
NewDLQHealthAdapter 创建 DLQ 健康检查适配器。 接受任意实现了 Stats() dlq.Stats 的队列,例如 *dlq.PayloadQueue 或 *dlq.PlatformEventQueue。
func (*DLQHealthAdapter) Stats ¶
func (a *DLQHealthAdapter) Stats() health.DLQStatsSnapshot
Stats 实现 health.DLQStats 接口,将 dlq.Stats 转换为 health.DLQStatsSnapshot
type Option ¶
type Option func(*Bot)
Option Bot 配置选项函数类型
func WithAdapter ¶
WithAdapter 将平台适配器注册到 Bot 的内部 Registry。
D3:Bot 不再有独立的 adapter 字段,所有适配器统一通过 platformRegistry 管理。 若 Bot 尚未初始化 Registry,此方法会自动创建。
func WithGoroutineThreshold ¶ added in v1.9.0
WithGoroutineThreshold 设置 RuntimeChecker 的 goroutine 阈值,超过此值时标记 Degraded。 阈值 <= 0 表示不限制。
func WithPprof ¶
func WithPprof(cfg PprofConfig) Option
WithPprof 注入 pprof 服务器,使其生命周期与 Bot 绑定(Start 时启动,Stop 时关闭)。
使用示例:
bot := remilia.NewBotBuilder().
WithOption(remilia.WithPprof(remilia.DefaultPprofConfig())).
Build()
type PprofConfig ¶
type PprofConfig struct {
// Enabled 是否启用 pprof
Enabled bool
// Addr 监听地址
Addr string
// AutoProfile 是否启用自动性能分析
AutoProfile bool
// ProfileInterval 自动分析间隔
ProfileInterval time.Duration
// ProfileDuration 每次分析持续时间
ProfileDuration time.Duration
// OutputDir 性能分析文件输出目录
OutputDir string
// EnableMutex 是否启用互斥锁分析
EnableMutex bool
// EnableBlock 是否启用阻塞分析
EnableBlock bool
// MutexProfileFraction 互斥锁分析采样率
MutexProfileFraction int
// BlockProfileRate 阻塞分析采样率
BlockProfileRate int
}
PprofConfig pprof 配置
type PprofServer ¶
type PprofServer struct {
// contains filtered or unexported fields
}
PprofServer pprof 服务器
func NewPprofServer ¶
func NewPprofServer(config PprofConfig) *PprofServer
NewPprofServer 创建 pprof 服务器
func (*PprofServer) AddHandler ¶ added in v1.4.0
func (p *PprofServer) AddHandler(path string, handler http.HandlerFunc)
AddHandler 注册一个额外的 HTTP handler 到 pprof 服务器的 mux。 必须在 Start() 之前调用。可用于注入 /health 等管理端点。
func (*PprofServer) ListenAddr ¶ added in v1.15.0
func (p *PprofServer) ListenAddr() string
ListenAddr 返回 pprof 服务器实际监听的地址。 若 config.Addr 为 :0,ListenAddr 会在 Start() 后返回实际分配的端口。
func (*PprofServer) Stop ¶
func (p *PprofServer) Stop(ctx context.Context) error
Stop 停止 pprof 服务器。
可安全地重复调用:Bot.Stop 本身是幂等的,Restart 也会先后触发多次 Stop。
func (*PprofServer) UpdateConfig ¶ added in v1.15.0
func (p *PprofServer) UpdateConfig(cfg PprofConfig)
UpdateConfig 运行时更新 pprof 配置(AutoProfile、ProfileInterval、ProfileDuration、EnableMutex、EnableBlock)。 注意:Enabled 和 Addr 不支持热更新。
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
Package api 提供 Remilia 框架的 RESTful 管理 API。
|
Package api 提供 Remilia 框架的 RESTful 管理 API。 |
|
client
Package client 提供 Remilia 管理 API 的 Go 客户端 SDK。
|
Package client 提供 Remilia 管理 API 的 Go 客户端 SDK。 |
|
builtin
|
|
|
acl
Package acl 提供独立的黑白名单(ACL)插件。
|
Package acl 提供独立的黑白名单(ACL)插件。 |
|
ai
Package ai 提供 AI 对话能力,支持多 LLM 提供商、工具调用与技能(Skill)系统。
|
Package ai 提供 AI 对话能力,支持多 LLM 提供商、工具调用与技能(Skill)系统。 |
|
antispam
Package antispam 提供反垃圾/防刷插件。
|
Package antispam 提供反垃圾/防刷插件。 |
|
broadcast
Package broadcast 提供广播/推送插件。
|
Package broadcast 提供广播/推送插件。 |
|
bundle
Package bundle 提供内置插件的批量注册入口。
|
Package bundle 提供内置插件的批量注册入口。 |
|
calendar
Package calendar 提供中国法定节假日数据和工作日计算工具。
|
Package calendar 提供中国法定节假日数据和工作日计算工具。 |
|
cooldown
Package cooldown 提供命令冷却时间插件。
|
Package cooldown 提供命令冷却时间插件。 |
|
core/permission
Package permission 是权限系统的**管理插件**,提供面向用户的命令界面。
|
Package permission 是权限系统的**管理插件**,提供面向用户的命令界面。 |
|
i18n
Package i18n 提供国际化/本地化插件。
|
Package i18n 提供国际化/本地化插件。 |
|
idiomdict
Package idiomdict 提供内嵌的中文成语词典。
|
Package idiomdict 提供内嵌的中文成语词典。 |
|
internal/jsonfile
Package jsonfile provides helpers for atomic JSON file persistence.
|
Package jsonfile provides helpers for atomic JSON file persistence. |
|
job
Package job 提供结构化的后台作业系统,与 builtin/scheduler 的区别:
|
Package job 提供结构化的后台作业系统,与 builtin/scheduler 的区别: |
|
keywordfilter
Package keywordfilter 提供关键词过滤插件。
|
Package keywordfilter 提供关键词过滤插件。 |
|
messagelog
Package messagelog 提供群消息历史记录功能,包含内存热缓存 + SQLite 持久化。
|
Package messagelog 提供群消息历史记录功能,包含内存热缓存 + SQLite 持久化。 |
|
pluginctrl
Package pluginctrl 提供逐群/逐用户的插件开关管理,并支持持久化。
|
Package pluginctrl 提供逐群/逐用户的插件开关管理,并支持持久化。 |
|
pluginstore
Package pluginstore 提供插件配置持久化插件。
|
Package pluginstore 提供插件配置持久化插件。 |
|
ratelimitui
Package ratelimitui 提供限流状态查询插件。
|
Package ratelimitui 提供限流状态查询插件。 |
|
scheduler
Package scheduler 提供计划任务插件。
|
Package scheduler 提供计划任务插件。 |
|
sendqueue
Package sendqueue provides an async message send queue with rate limiting.
|
Package sendqueue provides an async message send queue with rate limiting. |
|
stats
Package stats 提供用户行为统计插件。
|
Package stats 提供用户行为统计插件。 |
|
storage
Package storage 提供存储基础设施的插件系统集成适配器。
|
Package storage 提供存储基础设施的插件系统集成适配器。 |
|
subscription
Package subscription 提供通用的推送订阅框架。
|
Package subscription 提供通用的推送订阅框架。 |
|
verifycode
Package verifycode 提供独立的验证码插件。
|
Package verifycode 提供独立的验证码插件。 |
|
vevent
Package vevent 提供虚拟事件注入能力,允许插件或测试代码向引擎注入合成事件。
|
Package vevent 提供虚拟事件注入能力,允许插件或测试代码向引擎注入合成事件。 |
|
Package config 是框架的配置聚合与反序列化层。
|
Package config 是框架的配置聚合与反序列化层。 |
|
core
|
|
|
fsm
Package fsm 提供简单、并发安全的有限状态机(FSM)引擎, 专为 IM 机器人多步骤对话流程设计。
|
Package fsm 提供简单、并发安全的有限状态机(FSM)引擎, 专为 IM 机器人多步骤对话流程设计。 |
|
permission
Package permission provides the role-based access control (RBAC) system for the Remilia framework.
|
Package permission provides the role-based access control (RBAC) system for the Remilia framework. |
|
examples
|
|
|
async-tasks
command
|
|
|
basic-bot
command
|
|
|
benchmark
command
Package main provides a standalone throughput benchmark for the remilia framework.
|
Package main provides a standalone throughput benchmark for the remilia framework. |
|
command-bot
command
|
|
|
config-integration
command
|
|
|
config_hotreload
command
|
|
|
debug-subcommand-demo
command
|
|
|
discord-bot
command
Discord bot example demonstrating both connection methods.
|
Discord bot example demonstrating both connection methods. |
|
error-handling
command
|
|
|
help-discovery
command
|
|
|
logger-demo
command
|
|
|
metrics-monitoring
command
|
|
|
middleware-example
command
|
|
|
milky-bot
command
milky-bot demonstrates how to connect to a Milky QQ protocol server using the remilia bot framework.
|
milky-bot demonstrates how to connect to a Milky QQ protocol server using the remilia bot framework. |
|
onebot-bot
command
Package main demonstrates how to connect the remilia framework to an existing OneBot V11 implementation (e.g.
|
Package main demonstrates how to connect the remilia framework to an existing OneBot V11 implementation (e.g. |
|
plugin-example
command
|
|
|
plugin-v2-demo
command
|
|
|
production-ready
command
|
|
|
showcase
command
Package main 是 showcase 示例程序的入口。
|
Package main 是 showcase 示例程序的入口。 |
|
terminal-bot
command
Package main 提供终端 Bot 的交互式示例。
|
Package main 提供终端 Bot 的交互式示例。 |
|
textimage-demo
command
textimage-demo demonstrates the infra/textimage module by generating several example images that cover typical bot-message rendering scenarios.
|
textimage-demo demonstrates the infra/textimage module by generating several example images that cover typical bot-message rendering scenarios. |
|
tracing-demo
command
|
|
|
infra
|
|
|
atomic
Package atomic 提供对 sync/atomic 原语的类型安全封装。
|
Package atomic 提供对 sync/atomic 原语的类型安全封装。 |
|
audit
Package audit 提供结构化审计日志功能。
|
Package audit 提供结构化审计日志功能。 |
|
cache
Package cache 提供框架级通用缓存工具。
|
Package cache 提供框架级通用缓存工具。 |
|
coredump
Package coredump 提供在程序崩溃时生成核心转储(core dump)的能力。
|
Package coredump 提供在程序崩溃时生成核心转储(core dump)的能力。 |
|
expr
Package expr 提供安全的数学表达式求值工具。
|
Package expr 提供安全的数学表达式求值工具。 |
|
fs
Package fs 提供框架级文件系统工具。
|
Package fs 提供框架级文件系统工具。 |
|
future
Package future 提供泛型 Future,用于异步操作的结果传递。
|
Package future 提供泛型 Future,用于异步操作的结果传递。 |
|
gif
Package gif 提供逐帧 GIF 动图编码器。
|
Package gif 提供逐帧 GIF 动图编码器。 |
|
health
Package health 提供统一的健康检查树(HealthTree)模型。
|
Package health 提供统一的健康检查树(HealthTree)模型。 |
|
kv
Package kv 提供基于 LevelDB 的键值存储抽象。
|
Package kv 提供基于 LevelDB 的键值存储抽象。 |
|
logger
Package logger 提供结构化日志功能。
|
Package logger 提供结构化日志功能。 |
|
option
Package option 提供通用的选项模式工具函数。
|
Package option 提供通用的选项模式工具函数。 |
|
server
Package server 提供HTTP服务器封装和生命周期管理。
|
Package server 提供HTTP服务器封装和生命周期管理。 |
|
storage
Package storage 提供统一的持久化存储抽象层。
|
Package storage 提供统一的持久化存储抽象层。 |
|
syncx
Package syncx 提供泛型并发数据结构,是标准库 sync 包的类型安全扩展。
|
Package syncx 提供泛型并发数据结构,是标准库 sync 包的类型安全扩展。 |
|
textimage
Package textimage 将文本字符串(以及文本与图片的混合布局)转换为 适合通过聊天机器人平台发送的光栅图像。
|
Package textimage 将文本字符串(以及文本与图片的混合布局)转换为 适合通过聊天机器人平台发送的光栅图像。 |
|
tracing
Package tracing 提供基于 OpenTelemetry 的分布式追踪支持。
|
Package tracing 提供基于 OpenTelemetry 的分布式追踪支持。 |
|
trie
Package trie 提供泛型前缀树(Trie)与 Aho-Corasick 自动机。
|
Package trie 提供泛型前缀树(Trie)与 Aho-Corasick 自动机。 |
|
webimage
Package webimage 通过可注入的 Renderer 接口提供 HTML→图片渲染能力。
|
Package webimage 通过可注入的 Renderer 接口提供 HTML→图片渲染能力。 |
|
zhtext
Package zhtext 提供面向中文 Bot 场景的轻量级文本处理工具集。
|
Package zhtext 提供面向中文 Bot 场景的轻量级文本处理工具集。 |
|
Package lifecycle 提供改进的组件生命周期管理功能
|
Package lifecycle 提供改进的组件生命周期管理功能 |
|
hotreload
Package hotreload 提供配置热更新到中间件的传播桥接。
|
Package hotreload 提供配置热更新到中间件的传播桥接。 |
|
sender
Package sender 提供 platform.Sender 的装饰器(中间件)实现。
|
Package sender 提供 platform.Sender 的装饰器(中间件)实现。 |
|
Package platform 定义平台无关的消息与事件抽象层。
|
Package platform 定义平台无关的消息与事件抽象层。 |
|
discord
Package discord is the Discord platform.Adapter implementation.
|
Package discord is the Discord platform.Adapter implementation. |
|
milky
Package milky 实现了 remilia 机器人框架的 Milky QQ 协议适配器。
|
Package milky 实现了 remilia 机器人框架的 Milky QQ 协议适配器。 |
|
mock
Package mock provides shared mock implementations of platform interfaces for testing.
|
Package mock provides shared mock implementations of platform interfaces for testing. |
|
onebot
Package onebot 实现了 remilia 框架的 OneBot V11 协议适配器。
|
Package onebot 实现了 remilia 框架的 OneBot V11 协议适配器。 |
|
qq
Package qq 是 QQ 官方机器人平台的 platform.Adapter 实现。
|
Package qq 是 QQ 官方机器人平台的 platform.Adapter 实现。 |
|
qq/miniapp
Package miniapp 提供 QQ 频道小程序(MiniApp)开放数据加解密与签名验证工具。
|
Package miniapp 提供 QQ 频道小程序(MiniApp)开放数据加解密与签名验证工具。 |
|
qq/openapi
Package openapi 提供 QQ 机器人 OpenAPI 客户端。
|
Package openapi 提供 QQ 机器人 OpenAPI 客户端。 |
|
satori
Package satori 实现了基于 Satori 协议的 platform.Adapter, 可连接任意兼容 Satori 协议的 SDK(如 Chronocat、Lagrange、Koishi 等)。
|
Package satori 实现了基于 Satori 协议的 platform.Adapter, 可连接任意兼容 Satori 协议的 SDK(如 Chronocat、Lagrange、Koishi 等)。 |
|
telegram
Package telegram implements the Telegram Bot API platform adapter for remilia.
|
Package telegram implements the Telegram Bot API platform adapter for remilia. |
|
terminal
Package terminal 提供基于终端/控制台的平台适配器,用于调试和分析。
|
Package terminal 提供基于终端/控制台的平台适配器,用于调试和分析。 |
|
wechat
Package wechat is the platform.Adapter skeleton for WeChat Work / WeChat Official Account.
|
Package wechat is the platform.Adapter skeleton for WeChat Work / WeChat Official Account. |
|
Package plugin 提供插件系统的核心接口和实现。
|
Package plugin 提供插件系统的核心接口和实现。 |
|
plugintest
Package plugintest 提供插件单元测试辅助工具。
|
Package plugintest 提供插件单元测试辅助工具。 |
|
wasm
Package wasm 提供基于 wazero 的 WASM 插件运行时, 允许第三方插件以 .wasm 模块形式在沙箱中运行。
|
Package wasm 提供基于 wazero 的 WASM 插件运行时, 允许第三方插件以 .wasm 模块形式在沙箱中运行。 |
|
Package router 提供优先级驱动的路由分发层。
|
Package router 提供优先级驱动的路由分发层。 |
|
Package stats 提供零依赖的基础统计原语,供框架内部组件使用。
|
Package stats 提供零依赖的基础统计原语,供框架内部组件使用。 |
|
Package testbot provides platform-agnostic test helpers for Remilia Bot Framework.
|
Package testbot provides platform-agnostic test helpers for Remilia Bot Framework. |