Compare commits
2 Commits
d16261e6bd
...
fb5fae1524
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
fb5fae1524 | ||
|
|
64cd81b7f1 |
@@ -1,209 +0,0 @@
|
||||
---
|
||||
name: cellbot-multibot-server
|
||||
overview: 基于Go语言的多机器人服务端,参考OneBot12协议设计通用框架,采用分层架构和依赖注入设计模式。
|
||||
todos:
|
||||
- id: setup-project
|
||||
content: 初始化Go模块项目结构,创建基础目录和go.mod
|
||||
status: completed
|
||||
- id: implement-config
|
||||
content: 实现配置模块,支持TOML解析和fsnotify热重载
|
||||
status: completed
|
||||
dependencies:
|
||||
- setup-project
|
||||
- id: define-protocol
|
||||
content: 定义通用协议接口,提取OneBot12核心设计理念
|
||||
status: completed
|
||||
dependencies:
|
||||
- setup-project
|
||||
- id: build-eventbus
|
||||
content: 实现基于channel的高性能事件总线
|
||||
status: completed
|
||||
dependencies:
|
||||
- define-protocol
|
||||
- id: create-di-container
|
||||
content: 集成Uber Fx依赖注入容器,管理应用生命周期
|
||||
status: completed
|
||||
dependencies:
|
||||
- implement-config
|
||||
- build-eventbus
|
||||
- id: implement-fasthttp
|
||||
content: 封装fasthttp网络层,处理连接和通信
|
||||
status: completed
|
||||
dependencies:
|
||||
- create-di-container
|
||||
- id: unit-tests
|
||||
content: 编写核心模块的单元测试和并发基准测试
|
||||
status: completed
|
||||
dependencies:
|
||||
- build-eventbus
|
||||
- implement-config
|
||||
---
|
||||
|
||||
## Product Overview
|
||||
|
||||
基于Go语言构建的高性能、可扩展的多机器人服务端,参考OneBot12协议的设计理念,旨在提供统一的机器人管理与消息分发框架。
|
||||
|
||||
## Core Features
|
||||
|
||||
- **协议适配层**:提取OneBot12核心设计,支持通用接口定义与扩展
|
||||
- **多机器人管理**:支持同时连接和管理多个不同实现的机器人实例
|
||||
- **事件总线**:基于channel的高性能发布订阅机制,实现模块间解耦通信
|
||||
- **依赖注入容器**:管理组件生命周期,降低耦合度
|
||||
- **配置管理**:支持TOML格式配置,具备热重载能力
|
||||
- **反向WebSocket**:支持高性能反向WebSocket通信连接
|
||||
|
||||
## Tech Stack
|
||||
|
||||
- **语言**: Go 1.21+
|
||||
- **网络库**: fasthttp (valyala/fasthttp)
|
||||
- **配置**: BurntSushi/toml + fsnotify (热重载)
|
||||
- **依赖注入**: Uber-go/fx 或 uber-go/dig
|
||||
- **测试**: 标准库 testing + testify
|
||||
- **日志**: uber-go/zap
|
||||
|
||||
## Tech Architecture
|
||||
|
||||
### System Architecture
|
||||
|
||||
采用分层架构结合依赖注入模式。
|
||||
|
||||
- **协议层**: 定义OneBot12通用接口规范。
|
||||
- **适配层**: 实现不同平台的具体协议适配。
|
||||
- **核心层**: 事件总线、生命周期管理、依赖注入容器。
|
||||
- **网络层**: 基于fasthttp的高并发连接处理。
|
||||
|
||||
```mermaid
|
||||
graph TD
|
||||
A[Client/Bot] -->|WebSocket/TCP| B[Network Layer: fasthttp]
|
||||
B --> C[Adapter Layer: Protocol Implementation]
|
||||
C -->|Event Message| D[Event Bus: Channel Pub/Sub]
|
||||
D --> E[Core Layer: Business Logic]
|
||||
F[Config Manager: TOML + Hot Reload] --> E
|
||||
G[DI Container: fx/dig] --> B
|
||||
G --> C
|
||||
G --> D
|
||||
G --> E
|
||||
```
|
||||
|
||||
### Module Division
|
||||
|
||||
- **internal/protocol**: 定义OneBot12核心接口(Event, Action, API)。
|
||||
- **internal/adapter**: 协议适配器实现(如OneBot11适配器)。
|
||||
- **internal/engine**: 核心引擎,包含事件总线与Bot管理。
|
||||
- **internal/config**: 配置加载与热重载逻辑。
|
||||
- **internal/di**: 依赖注入容器封装。
|
||||
- **pkg/fasthttp**: fasthttp网络服务封装。
|
||||
|
||||
### Data Flow
|
||||
|
||||
外部连接 -> fasthttp处理 -> 协议适配器解析 -> 事件总线分发 -> 订阅者处理 -> 结果返回。
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
A[Incoming Message] --> B[fasthttp Handler]
|
||||
B --> C[Adapter Parse]
|
||||
C --> D{Event Bus Channel}
|
||||
D -->|Subscribe| E[Handler 1]
|
||||
D -->|Subscribe| F[Handler 2]
|
||||
E --> G[Response]
|
||||
F --> G
|
||||
```
|
||||
|
||||
## Implementation Details
|
||||
|
||||
### Core Directory Structure
|
||||
|
||||
```
|
||||
cellbot-multibot-server/
|
||||
├── cmd/
|
||||
│ └── server/
|
||||
│ └── main.go # 程序入口,注入fx应用
|
||||
├── internal/
|
||||
│ ├── config/ # 配置模块
|
||||
│ │ ├── config.go # 配置结构体定义
|
||||
│ │ └── loader.go # TOML加载与fsnotify热重载
|
||||
│ ├── protocol/ # 通用协议层
|
||||
│ │ └── onebot12.go # 核心接口定义
|
||||
│ ├── adapter/ # 适配器层
|
||||
│ │ ├── base.go # 适配器基类
|
||||
│ │ └── onebot11.go # OneBot11实现示例
|
||||
│ ├── engine/ # 核心引擎
|
||||
│ │ ├── eventbus.go # Channel发布订阅
|
||||
│ │ └── bot.go # 机器人实例管理
|
||||
│ └── di/ # 依赖注入
|
||||
│ └── wire.go # Provider定义
|
||||
├── pkg/
|
||||
│ └── net/ # 网络封装
|
||||
│ └── server.go # fasthttp服务器封装
|
||||
├── configs/
|
||||
│ └── config.toml # 默认配置文件
|
||||
└── go.mod
|
||||
```
|
||||
|
||||
### Key Code Structures
|
||||
|
||||
**Event Bus (Channel-based)**: 使用类型安全的channel进行事件分发,支持并发订阅与取消订阅。
|
||||
|
||||
```
|
||||
type EventBus struct {
|
||||
subscribers map[string][]chan Event
|
||||
mu sync.RWMutex
|
||||
}
|
||||
|
||||
func (eb *EventBus) Publish(eventType string, event Event) {
|
||||
// 发布逻辑
|
||||
}
|
||||
|
||||
func (eb *EventBus) Subscribe(eventType string) chan Event {
|
||||
// 订阅逻辑
|
||||
}
|
||||
```
|
||||
|
||||
**Dependency Injection (Fx)**: 使用Uber Fx管理应用生命周期,提供优雅的启动与关闭。
|
||||
|
||||
```
|
||||
// 提供Config实例
|
||||
func ProvideConfig() *Config {
|
||||
return LoadConfig("config.toml")
|
||||
}
|
||||
|
||||
// 提供EventBus实例
|
||||
func ProvideEventBus() *EventBus {
|
||||
return NewEventBus()
|
||||
}
|
||||
```
|
||||
|
||||
### Technical Implementation Plan
|
||||
|
||||
1. **配置与热重载**
|
||||
|
||||
- 定义Config结构体,支持TOML映射。
|
||||
- 使用fsnotify监听文件变化,实现平滑热重载。
|
||||
|
||||
2. **通用协议框架**
|
||||
|
||||
- 抽象OneBot12核心概念:Action, Event, API。
|
||||
- 定义统一的接口契约。
|
||||
|
||||
3. **事件总线设计**
|
||||
|
||||
- 基于buffered channel实现高吞吐量。
|
||||
- 实现带类型检查的订阅机制。
|
||||
|
||||
4. **fasthttp集成**
|
||||
|
||||
- 封装fasthttp Server,处理WebSocket升级。
|
||||
- 实现连接池管理以优化性能。
|
||||
|
||||
5. **测试策略**
|
||||
|
||||
- 单元测试覆盖核心逻辑(EventBus, Config)。
|
||||
- 基准测试验证并发性能。
|
||||
|
||||
## Agent Extensions
|
||||
|
||||
### SubAgent
|
||||
|
||||
- **code-explorer**
|
||||
- Purpose: 搜索和分析现有项目结构,确保新代码与现有模式一致
|
||||
- Expected outcome: 确认当前目录结构和代码风格,生成符合规范的代码
|
||||
3
.gitignore
vendored
3
.gitignore
vendored
@@ -39,3 +39,6 @@ logs/
|
||||
|
||||
# Config (local overrides)
|
||||
config/local.toml
|
||||
|
||||
# Database
|
||||
data/
|
||||
@@ -1,306 +0,0 @@
|
||||
# CellBot 插件开发指南
|
||||
|
||||
## 快速开始
|
||||
|
||||
CellBot 提供了类似 ZeroBot 风格的插件注册方式,可以在一个包内注册多个处理函数。
|
||||
|
||||
### ZeroBot 风格(推荐)
|
||||
|
||||
在 `init` 函数中使用 `OnXXX().Handle()` 注册处理函数,一个包内可以注册多个:
|
||||
|
||||
```go
|
||||
package echo
|
||||
|
||||
import (
|
||||
"context"
|
||||
"cellbot/internal/engine"
|
||||
"cellbot/internal/protocol"
|
||||
"go.uber.org/zap"
|
||||
)
|
||||
|
||||
func init() {
|
||||
// 处理私聊消息
|
||||
engine.OnPrivateMessage().
|
||||
Handle(func(ctx context.Context, event protocol.Event, botManager *protocol.BotManager, logger *zap.Logger) error {
|
||||
data := event.GetData()
|
||||
message := data["message"]
|
||||
userID := data["user_id"]
|
||||
|
||||
// 获取 bot 实例
|
||||
bot, _ := botManager.Get(event.GetSelfID())
|
||||
|
||||
// 发送回复
|
||||
action := &protocol.BaseAction{
|
||||
Type: protocol.ActionTypeSendPrivateMessage,
|
||||
Params: map[string]interface{}{
|
||||
"user_id": userID,
|
||||
"message": message,
|
||||
},
|
||||
}
|
||||
|
||||
return bot.SendAction(ctx, action)
|
||||
})
|
||||
|
||||
// 可以继续注册更多处理函数
|
||||
engine.OnGroupMessage().
|
||||
Handle(func(ctx context.Context, event protocol.Event, botManager *protocol.BotManager, logger *zap.Logger) error {
|
||||
// 处理群消息
|
||||
return nil
|
||||
})
|
||||
|
||||
// 处理命令
|
||||
engine.OnCommand("/help").
|
||||
Handle(func(ctx context.Context, event protocol.Event, botManager *protocol.BotManager, logger *zap.Logger) error {
|
||||
// 处理 /help 命令
|
||||
return nil
|
||||
})
|
||||
}
|
||||
```
|
||||
|
||||
**注意**:需要在 `internal/di/providers.go` 中导入插件包以触发 `init` 函数:
|
||||
|
||||
```go
|
||||
import (
|
||||
_ "cellbot/internal/plugins/echo" // 导入插件以触发 init
|
||||
)
|
||||
```
|
||||
|
||||
### 方式二:传统方式
|
||||
|
||||
实现 `protocol.EventHandler` 接口:
|
||||
|
||||
```go
|
||||
package myplugin
|
||||
|
||||
import (
|
||||
"context"
|
||||
"cellbot/internal/protocol"
|
||||
"go.uber.org/zap"
|
||||
)
|
||||
|
||||
type MyPlugin struct {
|
||||
logger *zap.Logger
|
||||
botManager *protocol.BotManager
|
||||
}
|
||||
|
||||
func NewMyPlugin(logger *zap.Logger, botManager *protocol.BotManager) *MyPlugin {
|
||||
return &MyPlugin{
|
||||
logger: logger.Named("my-plugin"),
|
||||
botManager: botManager,
|
||||
}
|
||||
}
|
||||
|
||||
func (p *MyPlugin) Name() string {
|
||||
return "MyPlugin"
|
||||
}
|
||||
|
||||
func (p *MyPlugin) Description() string {
|
||||
return "我的插件"
|
||||
}
|
||||
|
||||
func (p *MyPlugin) Priority() int {
|
||||
return 100
|
||||
}
|
||||
|
||||
func (p *MyPlugin) Match(event protocol.Event) bool {
|
||||
return event.GetType() == protocol.EventTypeMessage
|
||||
}
|
||||
|
||||
func (p *MyPlugin) Handle(ctx context.Context, event protocol.Event) error {
|
||||
// 处理逻辑
|
||||
return nil
|
||||
}
|
||||
```
|
||||
|
||||
## 内置匹配器
|
||||
|
||||
提供了以下便捷的匹配器函数:
|
||||
|
||||
- `engine.OnPrivateMessage()` - 匹配私聊消息
|
||||
- `engine.OnGroupMessage()` - 匹配群消息
|
||||
- `engine.OnMessage()` - 匹配所有消息
|
||||
- `engine.OnNotice()` - 匹配通知事件
|
||||
- `engine.OnRequest()` - 匹配请求事件
|
||||
- `engine.OnCommand(prefix)` - 匹配命令(以指定前缀开头)
|
||||
- `engine.OnPrefix(prefix)` - 匹配以指定前缀开头的消息
|
||||
- `engine.OnSuffix(suffix)` - 匹配以指定后缀结尾的消息
|
||||
- `engine.OnKeyword(keyword)` - 匹配包含指定关键词的消息
|
||||
- `engine.On(matchFunc)` - 自定义匹配器
|
||||
|
||||
### 自定义匹配器
|
||||
|
||||
```go
|
||||
func init() {
|
||||
engine.On(func(event protocol.Event) bool {
|
||||
// 自定义匹配逻辑
|
||||
if event.GetType() != protocol.EventTypeMessage {
|
||||
return false
|
||||
}
|
||||
|
||||
data := event.GetData()
|
||||
message, ok := data["raw_message"].(string)
|
||||
if !ok {
|
||||
return false
|
||||
}
|
||||
|
||||
// 只匹配以 "/" 开头的消息
|
||||
return len(message) > 0 && message[0] == '/'
|
||||
}).
|
||||
Priority(50). // 可以设置优先级
|
||||
Handle(func(ctx context.Context, event protocol.Event, botManager *protocol.BotManager, logger *zap.Logger) error {
|
||||
// 处理命令
|
||||
return nil
|
||||
})
|
||||
}
|
||||
```
|
||||
|
||||
## 注册插件
|
||||
|
||||
插件通过 `init` 函数自动注册,只需在 `internal/di/providers.go` 中导入插件包:
|
||||
|
||||
```go
|
||||
import (
|
||||
_ "cellbot/internal/plugins/echo" // 导入插件以触发 init
|
||||
_ "cellbot/internal/plugins/other" // 可以导入多个插件包
|
||||
)
|
||||
```
|
||||
|
||||
插件会在应用启动时自动加载,无需手动注册。
|
||||
|
||||
## 插件优先级
|
||||
|
||||
优先级数值越小,越先执行。建议:
|
||||
|
||||
- 0-50: 高优先级(预处理、权限检查等)
|
||||
- 51-100: 中等优先级(普通功能插件)
|
||||
- 101-200: 低优先级(日志记录、统计等)
|
||||
|
||||
## 完整示例
|
||||
|
||||
### 示例 1:关键词回复插件
|
||||
|
||||
```go
|
||||
package keyword
|
||||
|
||||
import (
|
||||
"context"
|
||||
"cellbot/internal/engine"
|
||||
"cellbot/internal/protocol"
|
||||
"go.uber.org/zap"
|
||||
)
|
||||
|
||||
func init() {
|
||||
keywords := map[string]string{
|
||||
"你好": "你好呀!",
|
||||
"再见": "再见~",
|
||||
"帮助": "发送 /help 查看帮助",
|
||||
}
|
||||
|
||||
engine.OnMessage().
|
||||
Priority(80).
|
||||
Handle(func(ctx context.Context, event protocol.Event, botManager *protocol.BotManager, logger *zap.Logger) error {
|
||||
data := event.GetData()
|
||||
message, ok := data["raw_message"].(string)
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
|
||||
// 检查关键词
|
||||
reply, found := keywords[message]
|
||||
if !found {
|
||||
return nil
|
||||
}
|
||||
|
||||
// 获取 bot 和用户信息
|
||||
bot, _ := botManager.Get(event.GetSelfID())
|
||||
userID := data["user_id"]
|
||||
|
||||
// 发送回复
|
||||
action := &protocol.BaseAction{
|
||||
Type: protocol.ActionTypeSendPrivateMessage,
|
||||
Params: map[string]interface{}{
|
||||
"user_id": userID,
|
||||
"message": reply,
|
||||
},
|
||||
}
|
||||
|
||||
_, err := bot.SendAction(ctx, action)
|
||||
return err
|
||||
})
|
||||
}
|
||||
```
|
||||
|
||||
### 示例 2:命令插件
|
||||
|
||||
```go
|
||||
func RegisterCommandPlugin(registry *engine.PluginRegistry, botManager *protocol.BotManager, logger *zap.Logger) {
|
||||
plugin := engine.NewPlugin("CommandPlugin").
|
||||
Description("命令处理插件").
|
||||
Priority(50).
|
||||
Match(func(event protocol.Event) bool {
|
||||
if event.GetType() != protocol.EventTypeMessage {
|
||||
return false
|
||||
}
|
||||
data := event.GetData()
|
||||
message, ok := data["raw_message"].(string)
|
||||
return ok && len(message) > 0 && message[0] == '/'
|
||||
}).
|
||||
Handle(func(ctx context.Context, event protocol.Event) error {
|
||||
data := event.GetData()
|
||||
message := data["raw_message"].(string)
|
||||
userID := data["user_id"]
|
||||
|
||||
bot, _ := botManager.Get(event.GetSelfID())
|
||||
|
||||
var reply string
|
||||
switch message {
|
||||
case "/help":
|
||||
reply = "可用命令:\n/help - 显示帮助\n/ping - 测试连接\n/time - 显示时间"
|
||||
case "/ping":
|
||||
reply = "pong!"
|
||||
case "/time":
|
||||
reply = time.Now().Format("2006-01-02 15:04:05")
|
||||
default:
|
||||
reply = "未知命令,发送 /help 查看帮助"
|
||||
}
|
||||
|
||||
action := &protocol.BaseAction{
|
||||
Type: protocol.ActionTypeSendPrivateMessage,
|
||||
Params: map[string]interface{}{
|
||||
"user_id": userID,
|
||||
"message": reply,
|
||||
},
|
||||
}
|
||||
|
||||
_, err := bot.SendAction(ctx, action)
|
||||
return err
|
||||
}).
|
||||
Build()
|
||||
|
||||
registry.Register(plugin)
|
||||
}
|
||||
```
|
||||
|
||||
## 最佳实践
|
||||
|
||||
1. **使用简化方式**:对于简单插件,使用 `engine.NewPlugin` 构建器
|
||||
2. **使用传统方式**:对于复杂插件(需要状态管理、配置等),使用传统方式
|
||||
3. **合理设置优先级**:确保插件按正确顺序执行
|
||||
4. **错误处理**:在 Handle 函数中妥善处理错误
|
||||
5. **日志记录**:使用 logger 记录关键操作
|
||||
6. **避免阻塞**:Handle 函数应快速返回,耗时操作应使用 goroutine
|
||||
|
||||
## 插件生命周期
|
||||
|
||||
插件在应用启动时注册,在应用运行期间持续监听事件。目前不支持热重载。
|
||||
|
||||
## 调试技巧
|
||||
|
||||
1. 使用 `logger.Debug` 记录调试信息
|
||||
2. 在 Match 函数中添加日志,确认匹配逻辑
|
||||
3. 检查事件数据结构,确保字段存在
|
||||
4. 使用 `zap.Any` 打印完整事件数据
|
||||
|
||||
```go
|
||||
logger.Debug("Event data", zap.Any("data", event.GetData()))
|
||||
```
|
||||
21
go.mod
21
go.mod
@@ -15,6 +15,25 @@ require (
|
||||
golang.org/x/time v0.14.0
|
||||
)
|
||||
|
||||
require github.com/robfig/cron/v3 v3.0.1
|
||||
|
||||
require (
|
||||
github.com/Tnze/go-mc v1.20.2 // indirect
|
||||
github.com/chromedp/cdproto v0.0.0-20250724212937-08a3db8b4327 // indirect
|
||||
github.com/chromedp/chromedp v0.14.2 // indirect
|
||||
github.com/chromedp/sysutil v1.1.0 // indirect
|
||||
github.com/go-json-experiment/json v0.0.0-20250725192818-e39067aee2d2 // indirect
|
||||
github.com/gobwas/httphead v0.1.0 // indirect
|
||||
github.com/gobwas/pool v0.2.1 // indirect
|
||||
github.com/gobwas/ws v1.4.0 // indirect
|
||||
github.com/jinzhu/inflection v1.0.0 // indirect
|
||||
github.com/jinzhu/now v1.1.5 // indirect
|
||||
github.com/mattn/go-sqlite3 v1.14.22 // indirect
|
||||
golang.org/x/text v0.21.0 // indirect
|
||||
gorm.io/driver/sqlite v1.6.0 // indirect
|
||||
gorm.io/gorm v1.31.1 // indirect
|
||||
)
|
||||
|
||||
require (
|
||||
github.com/andybalholm/brotli v1.1.1 // indirect
|
||||
github.com/bytedance/gopkg v0.1.3 // indirect
|
||||
@@ -30,5 +49,5 @@ require (
|
||||
go.uber.org/multierr v1.10.0 // indirect
|
||||
golang.org/x/arch v0.0.0-20210923205945-b76863e36670 // indirect
|
||||
golang.org/x/net v0.33.0 // indirect
|
||||
golang.org/x/sys v0.28.0 // indirect
|
||||
golang.org/x/sys v0.34.0 // indirect
|
||||
)
|
||||
|
||||
33
go.sum
33
go.sum
@@ -1,5 +1,7 @@
|
||||
github.com/BurntSushi/toml v1.3.2 h1:o7IhLm0Msx3BaB+n3Ag7L8EVlByGnpq14C4YWiu/gL8=
|
||||
github.com/BurntSushi/toml v1.3.2/go.mod h1:CxXYINrC8qIiEnFrOxCa7Jy5BFHlXnUU2pbicEuybxQ=
|
||||
github.com/Tnze/go-mc v1.20.2 h1:arHCE/WxLCxY73C/4ZNLdOymRYtdwoXE05ohB7HVN6Q=
|
||||
github.com/Tnze/go-mc v1.20.2/go.mod h1:geoRj2HsXSkB3FJBuhr7wCzXegRlzWsVXd7h7jiJ6aQ=
|
||||
github.com/andybalholm/brotli v1.1.1 h1:PR2pgnyFznKEugtsUo0xLdDop5SKXd5Qf5ysW+7XdTA=
|
||||
github.com/andybalholm/brotli v1.1.1/go.mod h1:05ib4cKhjx3OQYUY22hTVd34Bc8upXjOLL2rKwwZBoA=
|
||||
github.com/benbjohnson/clock v1.3.0 h1:ip6w0uFQkncKQ979AypyG0ER7mqUSBdKLOgAle/AT8A=
|
||||
@@ -10,6 +12,12 @@ github.com/bytedance/sonic v1.14.2 h1:k1twIoe97C1DtYUo+fZQy865IuHia4PR5RPiuGPPII
|
||||
github.com/bytedance/sonic v1.14.2/go.mod h1:T80iDELeHiHKSc0C9tubFygiuXoGzrkjKzX2quAx980=
|
||||
github.com/bytedance/sonic/loader v0.4.0 h1:olZ7lEqcxtZygCK9EKYKADnpQoYkRQxaeY2NYzevs+o=
|
||||
github.com/bytedance/sonic/loader v0.4.0/go.mod h1:AR4NYCk5DdzZizZ5djGqQ92eEhCCcdf5x77udYiSJRo=
|
||||
github.com/chromedp/cdproto v0.0.0-20250724212937-08a3db8b4327 h1:UQ4AU+BGti3Sy/aLU8KVseYKNALcX9UXY6DfpwQ6J8E=
|
||||
github.com/chromedp/cdproto v0.0.0-20250724212937-08a3db8b4327/go.mod h1:NItd7aLkcfOA/dcMXvl8p1u+lQqioRMq/SqDp71Pb/k=
|
||||
github.com/chromedp/chromedp v0.14.2 h1:r3b/WtwM50RsBZHMUm9fsNhhzRStTHrKdr2zmwbZSzM=
|
||||
github.com/chromedp/chromedp v0.14.2/go.mod h1:rHzAv60xDE7VNy/MYtTUrYreSc0ujt2O1/C3bzctYBo=
|
||||
github.com/chromedp/sysutil v1.1.0 h1:PUFNv5EcprjqXZD9nJb9b/c9ibAbxiYo4exNWZyipwM=
|
||||
github.com/chromedp/sysutil v1.1.0/go.mod h1:WiThHUdltqCNKGc4gaU50XgYjwjYIhKWoHGPTUfWTJ8=
|
||||
github.com/cloudwego/base64x v0.1.6 h1:t11wG9AECkCDk5fMSoxmufanudBtJ+/HemLstXDLI2M=
|
||||
github.com/cloudwego/base64x v0.1.6/go.mod h1:OFcloc187FXDaYHvrNIjxSe8ncn0OOM8gEHfghB2IPU=
|
||||
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
@@ -19,14 +27,30 @@ github.com/fasthttp/websocket v1.5.12 h1:e4RGPpWW2HTbL3zV0Y/t7g0ub294LkiuXXUuTOU
|
||||
github.com/fasthttp/websocket v1.5.12/go.mod h1:I+liyL7/4moHojiOgUOIKEWm9EIxHqxZChS+aMFltyg=
|
||||
github.com/fsnotify/fsnotify v1.9.0 h1:2Ml+OJNzbYCTzsxtv8vKSFD9PbJjmhYF14k/jKC7S9k=
|
||||
github.com/fsnotify/fsnotify v1.9.0/go.mod h1:8jBTzvmWwFyi3Pb8djgCCO5IBqzKJ/Jwo8TRcHyHii0=
|
||||
github.com/go-json-experiment/json v0.0.0-20250725192818-e39067aee2d2 h1:iizUGZ9pEquQS5jTGkh4AqeeHCMbfbjeb0zMt0aEFzs=
|
||||
github.com/go-json-experiment/json v0.0.0-20250725192818-e39067aee2d2/go.mod h1:TiCD2a1pcmjd7YnhGH0f/zKNcCD06B029pHhzV23c2M=
|
||||
github.com/gobwas/httphead v0.1.0 h1:exrUm0f4YX0L7EBwZHuCF4GDp8aJfVeBrlLQrs6NqWU=
|
||||
github.com/gobwas/httphead v0.1.0/go.mod h1:O/RXo79gxV8G+RqlR/otEwx4Q36zl9rqC5u12GKvMCM=
|
||||
github.com/gobwas/pool v0.2.1 h1:xfeeEhW7pwmX8nuLVlqbzVc7udMDrwetjEv+TZIz1og=
|
||||
github.com/gobwas/pool v0.2.1/go.mod h1:q8bcK0KcYlCgd9e7WYLm9LpyS+YeLd8JVDW6WezmKEw=
|
||||
github.com/gobwas/ws v1.4.0 h1:CTaoG1tojrh4ucGPcoJFiAQUAsEWekEWvLy7GsVNqGs=
|
||||
github.com/gobwas/ws v1.4.0/go.mod h1:G3gNqMNtPppf5XUz7O4shetPpcZ1VJ7zt18dlUeakrc=
|
||||
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
|
||||
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
||||
github.com/jinzhu/inflection v1.0.0 h1:K317FqzuhWc8YvSVlFMCCUb36O/S9MCKRDI7QkRKD/E=
|
||||
github.com/jinzhu/inflection v1.0.0/go.mod h1:h+uFLlag+Qp1Va5pdKtLDYj+kHp5pxUVkryuEj+Srlc=
|
||||
github.com/jinzhu/now v1.1.5 h1:/o9tlHleP7gOFmsnYNz3RGnqzefHA47wQpKrrdTIwXQ=
|
||||
github.com/jinzhu/now v1.1.5/go.mod h1:d3SSVoowX0Lcu0IBviAWJpolVfI5UJVZZ7cO71lE/z8=
|
||||
github.com/klauspost/compress v1.17.11 h1:In6xLpyWOi1+C7tXUUWv2ot1QvBjxevKAaI6IXrJmUc=
|
||||
github.com/klauspost/compress v1.17.11/go.mod h1:pMDklpSncoRMuLFrf1W9Ss9KT+0rH90U12bZKk7uwG0=
|
||||
github.com/klauspost/cpuid/v2 v2.2.9 h1:66ze0taIn2H33fBvCkXuv9BmCwDfafmiIVpKV9kKGuY=
|
||||
github.com/klauspost/cpuid/v2 v2.2.9/go.mod h1:rqkxqrZ1EhYM9G+hXH7YdowN5R5RGN6NK4QwQ3WMXF8=
|
||||
github.com/mattn/go-sqlite3 v1.14.22 h1:2gZY6PC6kBnID23Tichd1K+Z0oS6nE/XwU+Vz/5o4kU=
|
||||
github.com/mattn/go-sqlite3 v1.14.22/go.mod h1:Uh1q+B4BYcTPb+yiD3kU8Ct7aC0hY9fxUwlHK0RXw+Y=
|
||||
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||
github.com/robfig/cron/v3 v3.0.1 h1:WdRxkvbJztn8LMz/QEvLN5sBU+xKpSqwwUO1Pjr4qDs=
|
||||
github.com/robfig/cron/v3 v3.0.1/go.mod h1:eQICP3HwyT7UooqI/z+Ov+PtYAWygg1TEWWzGIFLtro=
|
||||
github.com/savsgio/gotils v0.0.0-20240704082632-aef3928b8a38 h1:D0vL7YNisV2yqE55+q0lFuGse6U8lxlg7fYTctlT5Gc=
|
||||
github.com/savsgio/gotils v0.0.0-20240704082632-aef3928b8a38/go.mod h1:sM7Mt7uEoCeFSCBM+qBrqvEo+/9vdmj19wzp3yzUhmg=
|
||||
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||
@@ -62,11 +86,20 @@ golang.org/x/arch v0.0.0-20210923205945-b76863e36670 h1:18EFjUmQOcUvxNYSkA6jO9VA
|
||||
golang.org/x/arch v0.0.0-20210923205945-b76863e36670/go.mod h1:5om86z9Hs0C8fWVUuoMHwpExlXzs5Tkyp9hOrfG7pp8=
|
||||
golang.org/x/net v0.33.0 h1:74SYHlV8BIgHIFC/LrYkOGIwL19eTYXQ5wc6TBuO36I=
|
||||
golang.org/x/net v0.33.0/go.mod h1:HXLR5J+9DxmrqMwG9qjGCxZ+zKXxBru04zlTvWlWuN4=
|
||||
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.28.0 h1:Fksou7UEQUWlKvIdsqzJmUmCX3cZuD2+P3XyyzwMhlA=
|
||||
golang.org/x/sys v0.28.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
||||
golang.org/x/sys v0.34.0 h1:H5Y5sJ2L2JRdyv7ROF1he/lPdvFsd0mJHFw2ThKHxLA=
|
||||
golang.org/x/sys v0.34.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k=
|
||||
golang.org/x/text v0.21.0 h1:zyQAAkrwaneQ066sspRyJaG9VNi/YJ1NfzcGB3hZ/qo=
|
||||
golang.org/x/text v0.21.0/go.mod h1:4IBbMaMmOPCJ8SecivzSH54+73PCFmPWxNTLm+vZkEQ=
|
||||
golang.org/x/time v0.14.0 h1:MRx4UaLrDotUKUdCIqzPC48t1Y9hANFKIRpNx+Te8PI=
|
||||
golang.org/x/time v0.14.0/go.mod h1:eL/Oa2bBBK0TkX57Fyni+NgnyQQN4LitPmob2Hjnqw4=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
||||
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
gorm.io/driver/sqlite v1.6.0 h1:WHRRrIiulaPiPFmDcod6prc4l2VGVWHz80KspNsxSfQ=
|
||||
gorm.io/driver/sqlite v1.6.0/go.mod h1:AO9V1qIQddBESngQUKWL9yoH93HIeA1X6V633rBwyT8=
|
||||
gorm.io/gorm v1.31.1 h1:7CA8FTFz/gRfgqgpeKIBcervUn3xSyPUmr6B2WXJ7kg=
|
||||
gorm.io/gorm v1.31.1/go.mod h1:XyQVbO2k6YkOis7C2437jSit3SsDK72s7n7rsSHd+Gs=
|
||||
|
||||
@@ -303,4 +303,4 @@ func BuildSetGroupCard(groupID, userID int64, card string) map[string]interface{
|
||||
"user_id": userID,
|
||||
"card": card,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -227,9 +227,23 @@ func (a *Adapter) SerializeAction(action protocol.Action) ([]byte, error) {
|
||||
zap.String("hint", "This action type may not be supported by OneBot11"))
|
||||
}
|
||||
|
||||
// 复制参数并转换消息链
|
||||
params := make(map[string]interface{})
|
||||
for k, v := range action.GetParams() {
|
||||
// 检查是否是消息链
|
||||
if k == "message" {
|
||||
if chain, ok := v.(protocol.MessageChain); ok {
|
||||
// 转换为 OneBot11 格式
|
||||
params[k] = ConvertMessageChainToOB11(chain)
|
||||
continue
|
||||
}
|
||||
}
|
||||
params[k] = v
|
||||
}
|
||||
|
||||
ob11Action := &OB11Action{
|
||||
Action: ob11ActionName,
|
||||
Params: action.GetParams(),
|
||||
Params: params,
|
||||
}
|
||||
|
||||
return sonic.Marshal(ob11Action)
|
||||
|
||||
238
internal/adapter/onebot11/message.go
Normal file
238
internal/adapter/onebot11/message.go
Normal file
@@ -0,0 +1,238 @@
|
||||
package onebot11
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"cellbot/internal/protocol"
|
||||
)
|
||||
|
||||
// ConvertMessageChainToOB11 将通用消息链转换为 OneBot11 格式
|
||||
func ConvertMessageChainToOB11(chain protocol.MessageChain) interface{} {
|
||||
if len(chain) == 0 {
|
||||
return ""
|
||||
}
|
||||
|
||||
// 转换为 OneBot11 消息段格式
|
||||
segments := make([]MessageSegment, 0, len(chain))
|
||||
for _, seg := range chain {
|
||||
ob11Seg := convertSegmentToOB11(seg)
|
||||
if ob11Seg != nil {
|
||||
segments = append(segments, *ob11Seg)
|
||||
}
|
||||
}
|
||||
|
||||
// 如果只有一个文本消息段,直接返回文本字符串
|
||||
if len(segments) == 1 && segments[0].Type == SegmentTypeText {
|
||||
if text, ok := segments[0].Data["text"].(string); ok {
|
||||
return text
|
||||
}
|
||||
}
|
||||
|
||||
return segments
|
||||
}
|
||||
|
||||
// convertSegmentToOB11 将通用消息段转换为 OneBot11 消息段
|
||||
func convertSegmentToOB11(seg protocol.MessageSegment) *MessageSegment {
|
||||
switch seg.Type {
|
||||
case protocol.SegmentTypeText:
|
||||
// 文本消息段
|
||||
return &MessageSegment{
|
||||
Type: SegmentTypeText,
|
||||
Data: map[string]interface{}{
|
||||
"text": seg.Data["text"],
|
||||
},
|
||||
}
|
||||
|
||||
case protocol.SegmentTypeMention:
|
||||
// @提及(OneBot12 -> OneBot11)
|
||||
userID := seg.Data["user_id"]
|
||||
return &MessageSegment{
|
||||
Type: SegmentTypeAt,
|
||||
Data: map[string]interface{}{
|
||||
"qq": userID,
|
||||
},
|
||||
}
|
||||
|
||||
case protocol.SegmentTypeAt:
|
||||
// OneBot11 兼容格式
|
||||
userID, ok := seg.Data["user_id"]
|
||||
if !ok {
|
||||
userID = seg.Data["qq"]
|
||||
}
|
||||
return &MessageSegment{
|
||||
Type: SegmentTypeAt,
|
||||
Data: map[string]interface{}{
|
||||
"qq": userID,
|
||||
},
|
||||
}
|
||||
|
||||
case protocol.SegmentTypeImage:
|
||||
// 图片消息段
|
||||
fileID, ok := seg.Data["file_id"].(string)
|
||||
if !ok {
|
||||
// 兼容 file 字段
|
||||
fileID, _ = seg.Data["file"].(string)
|
||||
}
|
||||
return &MessageSegment{
|
||||
Type: SegmentTypeImage,
|
||||
Data: map[string]interface{}{
|
||||
"file": fileID,
|
||||
},
|
||||
}
|
||||
|
||||
case protocol.SegmentTypeVoice:
|
||||
// 语音消息段(OneBot12 -> OneBot11)
|
||||
fileID, ok := seg.Data["file_id"].(string)
|
||||
if !ok {
|
||||
fileID, _ = seg.Data["file"].(string)
|
||||
}
|
||||
return &MessageSegment{
|
||||
Type: SegmentTypeRecord,
|
||||
Data: map[string]interface{}{
|
||||
"file": fileID,
|
||||
},
|
||||
}
|
||||
|
||||
case protocol.SegmentTypeRecord:
|
||||
// OneBot11 兼容格式
|
||||
fileID, ok := seg.Data["file"].(string)
|
||||
if !ok {
|
||||
fileID, _ = seg.Data["file_id"].(string)
|
||||
}
|
||||
return &MessageSegment{
|
||||
Type: SegmentTypeRecord,
|
||||
Data: map[string]interface{}{
|
||||
"file": fileID,
|
||||
},
|
||||
}
|
||||
|
||||
case protocol.SegmentTypeVideo:
|
||||
// 视频消息段
|
||||
fileID, ok := seg.Data["file_id"].(string)
|
||||
if !ok {
|
||||
fileID, _ = seg.Data["file"].(string)
|
||||
}
|
||||
return &MessageSegment{
|
||||
Type: SegmentTypeVideo,
|
||||
Data: map[string]interface{}{
|
||||
"file": fileID,
|
||||
},
|
||||
}
|
||||
|
||||
case protocol.SegmentTypeReply:
|
||||
// 回复消息段
|
||||
messageID := seg.Data["message_id"]
|
||||
return &MessageSegment{
|
||||
Type: SegmentTypeReply,
|
||||
Data: map[string]interface{}{
|
||||
"id": messageID,
|
||||
},
|
||||
}
|
||||
|
||||
case protocol.SegmentTypeFace:
|
||||
// 表情消息段
|
||||
faceID := seg.Data["id"]
|
||||
return &MessageSegment{
|
||||
Type: SegmentTypeFace,
|
||||
Data: map[string]interface{}{
|
||||
"id": faceID,
|
||||
},
|
||||
}
|
||||
|
||||
default:
|
||||
// 其他类型,尝试直接转换
|
||||
return &MessageSegment{
|
||||
Type: seg.Type,
|
||||
Data: seg.Data,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ConvertOB11ToMessageChain 将 OneBot11 消息段转换为通用消息链
|
||||
func ConvertOB11ToMessageChain(ob11Message interface{}) (protocol.MessageChain, error) {
|
||||
chain := protocol.MessageChain{}
|
||||
|
||||
// 如果是字符串,转换为文本消息段
|
||||
if str, ok := ob11Message.(string); ok {
|
||||
return protocol.NewMessageChain(protocol.NewTextSegment(str)), nil
|
||||
}
|
||||
|
||||
// 如果是数组,解析为消息段数组
|
||||
if segments, ok := ob11Message.([]MessageSegment); ok {
|
||||
for _, seg := range segments {
|
||||
genericSeg := convertOB11SegmentToGeneric(seg)
|
||||
chain = append(chain, genericSeg)
|
||||
}
|
||||
return chain, nil
|
||||
}
|
||||
|
||||
// 如果是接口数组,尝试转换
|
||||
if segments, ok := ob11Message.([]interface{}); ok {
|
||||
for _, seg := range segments {
|
||||
if segMap, ok := seg.(map[string]interface{}); ok {
|
||||
segType, _ := segMap["type"].(string)
|
||||
segData, _ := segMap["data"].(map[string]interface{})
|
||||
genericSeg := convertOB11SegmentToGeneric(MessageSegment{
|
||||
Type: segType,
|
||||
Data: segData,
|
||||
})
|
||||
chain = append(chain, genericSeg)
|
||||
}
|
||||
}
|
||||
return chain, nil
|
||||
}
|
||||
|
||||
return nil, fmt.Errorf("unsupported message format: %T", ob11Message)
|
||||
}
|
||||
|
||||
// convertOB11SegmentToGeneric 将 OneBot11 消息段转换为通用消息段
|
||||
func convertOB11SegmentToGeneric(seg MessageSegment) protocol.MessageSegment {
|
||||
switch seg.Type {
|
||||
case SegmentTypeText:
|
||||
return protocol.NewTextSegment(seg.Data["text"].(string))
|
||||
|
||||
case SegmentTypeAt:
|
||||
// OneBot11 @ 转换为 OneBot12 mention
|
||||
userID := seg.Data["qq"]
|
||||
return protocol.NewMentionSegment(userID)
|
||||
|
||||
case SegmentTypeImage:
|
||||
fileID, ok := seg.Data["file"].(string)
|
||||
if !ok {
|
||||
fileID, _ = seg.Data["file_id"].(string)
|
||||
}
|
||||
return protocol.NewImageSegment(fileID)
|
||||
|
||||
case SegmentTypeRecord:
|
||||
// OneBot11 record 转换为 OneBot12 voice
|
||||
fileID, ok := seg.Data["file"].(string)
|
||||
if !ok {
|
||||
fileID, _ = seg.Data["file_id"].(string)
|
||||
}
|
||||
return protocol.MessageSegment{
|
||||
Type: protocol.SegmentTypeVoice,
|
||||
Data: map[string]interface{}{
|
||||
"file_id": fileID,
|
||||
},
|
||||
}
|
||||
|
||||
case SegmentTypeReply:
|
||||
messageID := seg.Data["id"]
|
||||
return protocol.NewReplySegment(messageID)
|
||||
|
||||
case SegmentTypeFace:
|
||||
return protocol.MessageSegment{
|
||||
Type: protocol.SegmentTypeFace,
|
||||
Data: map[string]interface{}{
|
||||
"id": seg.Data["id"],
|
||||
},
|
||||
}
|
||||
|
||||
default:
|
||||
// 其他类型,直接转换
|
||||
return protocol.MessageSegment{
|
||||
Type: seg.Type,
|
||||
Data: seg.Data,
|
||||
}
|
||||
}
|
||||
}
|
||||
125
internal/database/database.go
Normal file
125
internal/database/database.go
Normal file
@@ -0,0 +1,125 @@
|
||||
package database
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sync"
|
||||
|
||||
"go.uber.org/zap"
|
||||
"gorm.io/driver/sqlite"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// Database 数据库接口,预留其他数据库接入
|
||||
type Database interface {
|
||||
// GetDB 获取指定 bot 的数据库连接(使用表前缀区分不同 bot 的数据)
|
||||
GetDB(botID string) (*gorm.DB, error)
|
||||
// Close 关闭所有数据库连接
|
||||
Close() error
|
||||
}
|
||||
|
||||
// SQLiteDatabase SQLite 数据库实现
|
||||
// 使用表前缀来区分不同 bot 的数据,所有 bot 共享同一个数据库文件和连接
|
||||
type SQLiteDatabase struct {
|
||||
mu sync.RWMutex
|
||||
db *gorm.DB // 共享的数据库连接
|
||||
dbs map[string]*gorm.DB // botID -> db (缓存,实际都指向同一个连接)
|
||||
logger *zap.Logger
|
||||
dbPath string
|
||||
options []gorm.Option
|
||||
}
|
||||
|
||||
// NewSQLiteDatabase 创建 SQLite 数据库实例
|
||||
// dbPath: 数据库文件路径(可以为空,使用默认路径)
|
||||
// 所有 bot 共享同一个数据库文件,通过表前缀区分
|
||||
func NewSQLiteDatabase(logger *zap.Logger, dbPath string, options ...gorm.Option) Database {
|
||||
if dbPath == "" {
|
||||
dbPath = "data/cellbot.db"
|
||||
}
|
||||
return &SQLiteDatabase{
|
||||
dbs: make(map[string]*gorm.DB),
|
||||
logger: logger.Named("database"),
|
||||
dbPath: dbPath,
|
||||
options: options,
|
||||
}
|
||||
}
|
||||
|
||||
// GetDB 获取指定 bot 的数据库连接
|
||||
// 使用表前缀来区分不同 bot 的数据,所有 bot 共享同一个数据库文件和连接
|
||||
func (d *SQLiteDatabase) GetDB(botID string) (*gorm.DB, error) {
|
||||
if botID == "" {
|
||||
return nil, fmt.Errorf("botID cannot be empty")
|
||||
}
|
||||
|
||||
// 初始化共享数据库连接(如果还没有)
|
||||
d.mu.Lock()
|
||||
if d.db == nil {
|
||||
// 确保数据库目录存在
|
||||
dir := filepath.Dir(d.dbPath)
|
||||
if err := os.MkdirAll(dir, 0755); err != nil {
|
||||
d.mu.Unlock()
|
||||
return nil, fmt.Errorf("failed to create database directory: %w", err)
|
||||
}
|
||||
|
||||
// 所有 bot 共享同一个数据库文件和连接
|
||||
// 通过表前缀区分不同 bot 的数据
|
||||
db, err := gorm.Open(sqlite.Open(d.dbPath), d.options...)
|
||||
if err != nil {
|
||||
d.mu.Unlock()
|
||||
return nil, fmt.Errorf("failed to open database: %w", err)
|
||||
}
|
||||
|
||||
d.db = db
|
||||
d.logger.Info("Shared database connection created",
|
||||
zap.String("db_path", d.dbPath))
|
||||
}
|
||||
d.mu.Unlock()
|
||||
|
||||
// 所有 bot 返回同一个连接(通过缓存避免重复查找)
|
||||
d.mu.RLock()
|
||||
if cached, ok := d.dbs[botID]; ok {
|
||||
d.mu.RUnlock()
|
||||
return cached, nil
|
||||
}
|
||||
d.mu.RUnlock()
|
||||
|
||||
// 缓存连接引用(实际都指向同一个连接)
|
||||
d.mu.Lock()
|
||||
if cached, ok := d.dbs[botID]; ok {
|
||||
d.mu.Unlock()
|
||||
return cached, nil
|
||||
}
|
||||
d.dbs[botID] = d.db
|
||||
d.mu.Unlock()
|
||||
|
||||
return d.db, nil
|
||||
}
|
||||
|
||||
// Close 关闭所有数据库连接
|
||||
func (d *SQLiteDatabase) Close() error {
|
||||
d.mu.Lock()
|
||||
defer d.mu.Unlock()
|
||||
|
||||
// 关闭共享的数据库连接
|
||||
if d.db != nil {
|
||||
if sqlDB, err := d.db.DB(); err == nil {
|
||||
if err := sqlDB.Close(); err != nil {
|
||||
d.logger.Error("Failed to close database", zap.Error(err))
|
||||
return err
|
||||
}
|
||||
}
|
||||
d.db = nil
|
||||
}
|
||||
|
||||
// 清空缓存
|
||||
d.dbs = make(map[string]*gorm.DB)
|
||||
|
||||
d.logger.Info("Database connection closed")
|
||||
return nil
|
||||
}
|
||||
|
||||
// GetDBPath 获取数据库文件路径
|
||||
func (d *SQLiteDatabase) GetDBPath() string {
|
||||
return d.dbPath
|
||||
}
|
||||
38
internal/database/table_prefix.go
Normal file
38
internal/database/table_prefix.go
Normal file
@@ -0,0 +1,38 @@
|
||||
package database
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// GetTableName 获取带前缀的表名
|
||||
// 格式:{botID}_{tableName}
|
||||
func GetTableName(botID, tableName string) string {
|
||||
if botID == "" {
|
||||
return tableName
|
||||
}
|
||||
// 清理 botID 中的特殊字符,确保表名合法
|
||||
cleanBotID := sanitizeTableName(botID)
|
||||
return fmt.Sprintf("%s_%s", cleanBotID, tableName)
|
||||
}
|
||||
|
||||
// WithTablePrefix 为查询添加表前缀
|
||||
func WithTablePrefix(db *gorm.DB, botID, tableName string) *gorm.DB {
|
||||
prefixedTableName := GetTableName(botID, tableName)
|
||||
return db.Table(prefixedTableName)
|
||||
}
|
||||
|
||||
// sanitizeTableName 清理表名中的特殊字符
|
||||
func sanitizeTableName(name string) string {
|
||||
// 移除或替换 SQL 不安全的字符
|
||||
result := ""
|
||||
for _, r := range name {
|
||||
if (r >= 'a' && r <= 'z') || (r >= 'A' && r <= 'Z') || (r >= '0' && r <= '9') || r == '_' {
|
||||
result += string(r)
|
||||
} else {
|
||||
result += "_"
|
||||
}
|
||||
}
|
||||
return result
|
||||
}
|
||||
@@ -2,12 +2,17 @@ package di
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"cellbot/internal/adapter/milky"
|
||||
"cellbot/internal/adapter/onebot11"
|
||||
"cellbot/internal/config"
|
||||
"cellbot/internal/database"
|
||||
"cellbot/internal/engine"
|
||||
_ "cellbot/internal/plugins/echo" // 导入插件以触发 init 函数
|
||||
"cellbot/internal/plugins/mcstatus"
|
||||
_ "cellbot/internal/plugins/mcstatus" // 导入插件以触发 init 函数
|
||||
_ "cellbot/internal/plugins/welcome" // 导入插件以触发 init 函数
|
||||
"cellbot/internal/protocol"
|
||||
"cellbot/pkg/net"
|
||||
|
||||
@@ -42,8 +47,12 @@ func ProvideEventBus(logger *zap.Logger) *engine.EventBus {
|
||||
return engine.NewEventBus(logger, 10000)
|
||||
}
|
||||
|
||||
func ProvideDispatcher(eventBus *engine.EventBus, logger *zap.Logger, cfg *config.Config) *engine.Dispatcher {
|
||||
dispatcher := engine.NewDispatcher(eventBus, logger)
|
||||
func ProvideScheduler(logger *zap.Logger) *engine.Scheduler {
|
||||
return engine.NewScheduler(logger)
|
||||
}
|
||||
|
||||
func ProvideDispatcher(eventBus *engine.EventBus, logger *zap.Logger, cfg *config.Config, scheduler *engine.Scheduler) *engine.Dispatcher {
|
||||
dispatcher := engine.NewDispatcherWithScheduler(eventBus, logger, scheduler)
|
||||
|
||||
// 注册限流中间件
|
||||
if cfg.Engine.RateLimit.Enabled {
|
||||
@@ -77,6 +86,52 @@ func ProvideServer(cfg *config.Config, logger *zap.Logger, botManager *protocol.
|
||||
return net.NewServer(cfg.Server.Host, cfg.Server.Port, logger, botManager, eventBus)
|
||||
}
|
||||
|
||||
// ProvideDatabase 提供数据库服务
|
||||
func ProvideDatabase(logger *zap.Logger) database.Database {
|
||||
return database.NewSQLiteDatabase(logger, "data/cellbot.db")
|
||||
}
|
||||
|
||||
// InitMCStatusDatabase 初始化 MC 状态插件的数据库
|
||||
func InitMCStatusDatabase(dbService database.Database, logger *zap.Logger, botManager *protocol.BotManager) error {
|
||||
// 为每个 bot 初始化数据库表
|
||||
bots := botManager.GetAll()
|
||||
for _, bot := range bots {
|
||||
botID := bot.GetID()
|
||||
db, err := dbService.GetDB(botID)
|
||||
if err != nil {
|
||||
logger.Error("Failed to get database for bot",
|
||||
zap.String("bot_id", botID),
|
||||
zap.Error(err))
|
||||
continue
|
||||
}
|
||||
|
||||
// 创建表(使用原始 SQL 避免循环依赖)
|
||||
// 注意:虽然使用 fmt.Sprintf,但 tableName 已经通过 sanitizeTableName 清理过,相对安全
|
||||
tableName := database.GetTableName(botID, "mc_server_binds")
|
||||
// 使用参数化查询更安全,但 SQLite 的 CREATE TABLE 不支持参数化表名
|
||||
// 所以这里使用清理过的表名是合理的
|
||||
if err := db.Exec(fmt.Sprintf(`
|
||||
CREATE TABLE IF NOT EXISTS %s (
|
||||
id TEXT PRIMARY KEY,
|
||||
server_ip TEXT NOT NULL
|
||||
)
|
||||
`, tableName)).Error; err != nil {
|
||||
logger.Error("Failed to create table",
|
||||
zap.String("bot_id", botID),
|
||||
zap.String("table", tableName),
|
||||
zap.Error(err))
|
||||
} else {
|
||||
logger.Info("Database table initialized",
|
||||
zap.String("bot_id", botID),
|
||||
zap.String("table", tableName))
|
||||
}
|
||||
}
|
||||
|
||||
// 初始化插件数据库
|
||||
mcstatus.InitDatabase(dbService)
|
||||
return nil
|
||||
}
|
||||
|
||||
func ProvideMilkyBots(cfg *config.Config, logger *zap.Logger, eventBus *engine.EventBus, wsManager *net.WebSocketManager, botManager *protocol.BotManager, lc fx.Lifecycle) error {
|
||||
for _, botCfg := range cfg.Bots {
|
||||
if botCfg.Protocol == "milky" && botCfg.Enabled {
|
||||
@@ -97,7 +152,18 @@ func ProvideMilkyBots(cfg *config.Config, logger *zap.Logger, eventBus *engine.E
|
||||
lc.Append(fx.Hook{
|
||||
OnStart: func(ctx context.Context) error {
|
||||
logger.Info("Starting Milky bot", zap.String("bot_id", botCfg.ID))
|
||||
return bot.Connect(ctx)
|
||||
// 在后台启动连接,失败时只记录错误,不终止应用
|
||||
go func() {
|
||||
if err := bot.Connect(context.Background()); err != nil {
|
||||
logger.Error("Failed to connect Milky bot, will retry in background",
|
||||
zap.String("bot_id", botCfg.ID),
|
||||
zap.Error(err))
|
||||
// 可以在这里实现重试逻辑
|
||||
} else {
|
||||
logger.Info("Milky bot connected successfully", zap.String("bot_id", botCfg.ID))
|
||||
}
|
||||
}()
|
||||
return nil
|
||||
},
|
||||
OnStop: func(ctx context.Context) error {
|
||||
logger.Info("Stopping Milky bot", zap.String("bot_id", botCfg.ID))
|
||||
@@ -137,7 +203,18 @@ func ProvideOneBot11Bots(cfg *config.Config, logger *zap.Logger, wsManager *net.
|
||||
lc.Append(fx.Hook{
|
||||
OnStart: func(ctx context.Context) error {
|
||||
logger.Info("Starting OneBot11 bot", zap.String("bot_id", botCfg.ID))
|
||||
return bot.Connect(ctx)
|
||||
// 在后台启动连接,失败时只记录错误,不终止应用
|
||||
go func() {
|
||||
if err := bot.Connect(context.Background()); err != nil {
|
||||
logger.Error("Failed to connect OneBot11 bot, will retry in background",
|
||||
zap.String("bot_id", botCfg.ID),
|
||||
zap.Error(err))
|
||||
// 可以在这里实现重试逻辑
|
||||
} else {
|
||||
logger.Info("OneBot11 bot connected successfully", zap.String("bot_id", botCfg.ID))
|
||||
}
|
||||
}()
|
||||
return nil
|
||||
},
|
||||
OnStop: func(ctx context.Context) error {
|
||||
logger.Info("Stopping OneBot11 bot", zap.String("bot_id", botCfg.ID))
|
||||
@@ -171,19 +248,28 @@ func LoadPlugins(logger *zap.Logger, botManager *protocol.BotManager, registry *
|
||||
zap.Strings("plugins", engine.GetRegisteredPlugins()))
|
||||
}
|
||||
|
||||
// LoadScheduledJobs 加载所有定时任务(由依赖注入系统调用)
|
||||
func LoadScheduledJobs(scheduler *engine.Scheduler, logger *zap.Logger) error {
|
||||
return engine.LoadAllJobs(scheduler, logger)
|
||||
}
|
||||
|
||||
var Providers = fx.Options(
|
||||
fx.Provide(
|
||||
ProvideConfig,
|
||||
ProvideConfigManager,
|
||||
ProvideLogger,
|
||||
ProvideEventBus,
|
||||
ProvideScheduler,
|
||||
ProvideDispatcher,
|
||||
ProvidePluginRegistry,
|
||||
ProvideBotManager,
|
||||
ProvideWebSocketManager,
|
||||
ProvideDatabase,
|
||||
ProvideServer,
|
||||
),
|
||||
fx.Invoke(ProvideMilkyBots),
|
||||
fx.Invoke(ProvideOneBot11Bots),
|
||||
fx.Invoke(LoadPlugins),
|
||||
fx.Invoke(LoadScheduledJobs),
|
||||
fx.Invoke(InitMCStatusDatabase),
|
||||
)
|
||||
|
||||
@@ -30,36 +30,29 @@ type Dispatcher struct {
|
||||
middlewares []protocol.Middleware
|
||||
logger *zap.Logger
|
||||
eventBus *EventBus
|
||||
scheduler *Scheduler
|
||||
metrics DispatcherMetrics
|
||||
mu sync.RWMutex
|
||||
workerPool chan struct{} // 工作池,限制并发数
|
||||
maxWorkers int
|
||||
async bool // 是否异步处理
|
||||
totalTime int64 // 总处理时间(纳秒)
|
||||
}
|
||||
|
||||
// NewDispatcher 创建事件分发器
|
||||
func NewDispatcher(eventBus *EventBus, logger *zap.Logger) *Dispatcher {
|
||||
return NewDispatcherWithConfig(eventBus, logger, 100, true)
|
||||
}
|
||||
|
||||
// NewDispatcherWithConfig 使用配置创建事件分发器
|
||||
func NewDispatcherWithConfig(eventBus *EventBus, logger *zap.Logger, maxWorkers int, async bool) *Dispatcher {
|
||||
if maxWorkers <= 0 {
|
||||
maxWorkers = 100
|
||||
}
|
||||
|
||||
return &Dispatcher{
|
||||
handlers: make([]protocol.EventHandler, 0),
|
||||
middlewares: make([]protocol.Middleware, 0),
|
||||
logger: logger.Named("dispatcher"),
|
||||
eventBus: eventBus,
|
||||
workerPool: make(chan struct{}, maxWorkers),
|
||||
maxWorkers: maxWorkers,
|
||||
async: async,
|
||||
}
|
||||
}
|
||||
|
||||
// NewDispatcherWithScheduler 创建带调度器的事件分发器
|
||||
func NewDispatcherWithScheduler(eventBus *EventBus, logger *zap.Logger, scheduler *Scheduler) *Dispatcher {
|
||||
dispatcher := NewDispatcher(eventBus, logger)
|
||||
dispatcher.scheduler = scheduler
|
||||
return dispatcher
|
||||
}
|
||||
|
||||
// RegisterHandler 注册事件处理器
|
||||
func (d *Dispatcher) RegisterHandler(handler protocol.EventHandler) {
|
||||
d.mu.Lock()
|
||||
@@ -114,39 +107,75 @@ func (d *Dispatcher) Start(ctx context.Context) {
|
||||
go d.eventLoop(ctx, eventChan)
|
||||
}
|
||||
|
||||
// 启动调度器
|
||||
if d.scheduler != nil {
|
||||
if err := d.scheduler.Start(); err != nil {
|
||||
d.logger.Error("Failed to start scheduler", zap.Error(err))
|
||||
} else {
|
||||
d.logger.Info("Scheduler started")
|
||||
}
|
||||
}
|
||||
|
||||
d.logger.Info("Dispatcher started")
|
||||
}
|
||||
|
||||
// Stop 停止分发器
|
||||
func (d *Dispatcher) Stop() {
|
||||
// 停止调度器
|
||||
if d.scheduler != nil {
|
||||
if err := d.scheduler.Stop(); err != nil {
|
||||
d.logger.Error("Failed to stop scheduler", zap.Error(err))
|
||||
} else {
|
||||
d.logger.Info("Scheduler stopped")
|
||||
}
|
||||
}
|
||||
|
||||
d.logger.Info("Dispatcher stopped")
|
||||
}
|
||||
|
||||
// GetScheduler 获取调度器
|
||||
func (d *Dispatcher) GetScheduler() *Scheduler {
|
||||
return d.scheduler
|
||||
}
|
||||
|
||||
// eventLoop 事件循环
|
||||
func (d *Dispatcher) eventLoop(ctx context.Context, eventChan chan protocol.Event) {
|
||||
// 使用独立的 context,避免应用关闭时取消正在处理的事件
|
||||
// 即使应用关闭,也要让正在处理的事件完成
|
||||
shutdown := false
|
||||
|
||||
for {
|
||||
select {
|
||||
case event, ok := <-eventChan:
|
||||
if !ok {
|
||||
d.logger.Info("Event channel closed, stopping event loop")
|
||||
return
|
||||
}
|
||||
|
||||
if d.IsAsync() {
|
||||
// 异步处理,使用工作池限制并发
|
||||
d.workerPool <- struct{}{} // 获取工作槽位
|
||||
go func(e protocol.Event) {
|
||||
defer func() {
|
||||
<-d.workerPool // 释放工作槽位
|
||||
}()
|
||||
d.handleEvent(ctx, e)
|
||||
}(event)
|
||||
} else {
|
||||
// 同步处理
|
||||
d.handleEvent(ctx, event)
|
||||
}
|
||||
d.logger.Debug("Event received in eventLoop",
|
||||
zap.String("type", string(event.GetType())),
|
||||
zap.String("detail_type", event.GetDetailType()),
|
||||
zap.String("self_id", event.GetSelfID()),
|
||||
zap.Bool("shutdown", shutdown))
|
||||
|
||||
// 为每个事件创建独立的 context,避免应用关闭时取消正在处理的事件
|
||||
// 使用独立的 context,允许处理完成
|
||||
handlerCtx, handlerCancel := context.WithTimeout(context.Background(), 5*time.Minute)
|
||||
|
||||
// 直接使用 goroutine 处理事件,Go 的调度器会自动管理
|
||||
go func(e protocol.Event) {
|
||||
defer handlerCancel()
|
||||
d.handleEvent(handlerCtx, e)
|
||||
}(event)
|
||||
|
||||
case <-ctx.Done():
|
||||
return
|
||||
// 当应用关闭时,标记为关闭状态,但继续处理 channel 中的事件
|
||||
if !shutdown {
|
||||
d.logger.Info("Context cancelled, will continue processing events until channel closes")
|
||||
shutdown = true
|
||||
}
|
||||
// 继续处理 channel 中的事件,直到 channel 关闭
|
||||
// 不再检查 ctx.Done(),只等待 channel 关闭
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -215,13 +244,16 @@ func (d *Dispatcher) createHandlerChain(ctx context.Context, event protocol.Even
|
||||
|
||||
for i, handler := range handlers {
|
||||
matched := handler.Match(event)
|
||||
d.logger.Info("Checking handler",
|
||||
d.logger.Debug("Checking handler",
|
||||
zap.Int("handler_index", i),
|
||||
zap.String("handler_name", handler.Name()),
|
||||
zap.Int("priority", handler.Priority()),
|
||||
zap.Bool("matched", matched))
|
||||
if matched {
|
||||
d.logger.Info("Handler matched, calling Handle",
|
||||
zap.Int("handler_index", i))
|
||||
zap.Int("handler_index", i),
|
||||
zap.String("handler_name", handler.Name()),
|
||||
zap.String("handler_description", handler.Description()))
|
||||
// 使用defer捕获单个handler的panic
|
||||
func() {
|
||||
defer func() {
|
||||
@@ -313,17 +345,3 @@ func (d *Dispatcher) LogMetrics() {
|
||||
zap.Int("handler_count", d.GetHandlerCount()),
|
||||
zap.Int("middleware_count", d.GetMiddlewareCount()))
|
||||
}
|
||||
|
||||
// SetAsync 设置是否异步处理
|
||||
func (d *Dispatcher) SetAsync(async bool) {
|
||||
d.mu.Lock()
|
||||
defer d.mu.Unlock()
|
||||
d.async = async
|
||||
}
|
||||
|
||||
// IsAsync 是否异步处理
|
||||
func (d *Dispatcher) IsAsync() bool {
|
||||
d.mu.RLock()
|
||||
defer d.mu.RUnlock()
|
||||
return d.async
|
||||
}
|
||||
|
||||
@@ -78,9 +78,10 @@ func (eb *EventBus) Stop() {
|
||||
|
||||
// Publish 发布事件
|
||||
func (eb *EventBus) Publish(event protocol.Event) {
|
||||
eb.logger.Info("Publishing event to channel",
|
||||
eb.logger.Debug("Publishing event to channel",
|
||||
zap.String("event_type", string(event.GetType())),
|
||||
zap.String("detail_type", event.GetDetailType()),
|
||||
zap.String("self_id", event.GetSelfID()),
|
||||
zap.Int("channel_len", len(eb.eventChan)),
|
||||
zap.Int("channel_cap", cap(eb.eventChan)))
|
||||
|
||||
@@ -88,8 +89,10 @@ func (eb *EventBus) Publish(event protocol.Event) {
|
||||
case eb.eventChan <- event:
|
||||
atomic.AddInt64(&eb.metrics.PublishedTotal, 1)
|
||||
atomic.StoreInt64(&eb.metrics.LastEventTime, time.Now().Unix())
|
||||
eb.logger.Info("Event successfully queued",
|
||||
zap.String("event_type", string(event.GetType())))
|
||||
eb.logger.Info("Event published successfully",
|
||||
zap.String("event_type", string(event.GetType())),
|
||||
zap.String("detail_type", event.GetDetailType()),
|
||||
zap.String("self_id", event.GetSelfID()))
|
||||
case <-eb.ctx.Done():
|
||||
atomic.AddInt64(&eb.metrics.DroppedTotal, 1)
|
||||
eb.logger.Warn("Event bus is shutting down, event dropped",
|
||||
@@ -240,7 +243,16 @@ func (eb *EventBus) dispatchEvent(event protocol.Event) {
|
||||
atomic.AddInt64(&eb.metrics.DroppedTotal, 1)
|
||||
eb.logger.Warn("Subscription channel full, event dropped",
|
||||
zap.String("sub_id", sub.ID),
|
||||
zap.String("event_type", key))
|
||||
zap.String("event_type", key),
|
||||
zap.String("detail_type", event.GetDetailType()),
|
||||
zap.String("raw_message", func() string {
|
||||
if data := event.GetData(); data != nil {
|
||||
if msg, ok := data["raw_message"].(string); ok {
|
||||
return msg
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}()))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@ package engine
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
|
||||
@@ -208,11 +209,16 @@ var (
|
||||
// HandlerFunc 处理函数类型(支持依赖注入)
|
||||
type HandlerFunc func(ctx context.Context, event protocol.Event, botManager *protocol.BotManager, logger *zap.Logger) error
|
||||
|
||||
// HandlerMiddleware 处理器中间件函数类型
|
||||
// 返回 true 表示通过中间件检查,false 表示不通过
|
||||
type HandlerMiddleware func(event protocol.Event) bool
|
||||
|
||||
// HandlerBuilder 处理器构建器(类似 ZeroBot 的 API)
|
||||
type HandlerBuilder struct {
|
||||
matchFunc func(protocol.Event) bool
|
||||
priority int
|
||||
handleFunc HandlerFunc
|
||||
matchFunc func(protocol.Event) bool
|
||||
priority int
|
||||
handleFunc HandlerFunc
|
||||
middlewares []HandlerMiddleware
|
||||
}
|
||||
|
||||
// OnPrivateMessage 匹配私聊消息
|
||||
@@ -246,20 +252,82 @@ func OnMessage() *HandlerBuilder {
|
||||
}
|
||||
|
||||
// OnNotice 匹配通知事件
|
||||
func OnNotice() *HandlerBuilder {
|
||||
// 用法:
|
||||
//
|
||||
// OnNotice() - 匹配所有通知事件
|
||||
// OnNotice("group_increase") - 匹配群成员增加事件
|
||||
// OnNotice("group_increase", "group_decrease") - 匹配群成员增加或减少事件
|
||||
func OnNotice(detailTypes ...string) *HandlerBuilder {
|
||||
return &HandlerBuilder{
|
||||
matchFunc: func(event protocol.Event) bool {
|
||||
return event.GetType() == protocol.EventTypeNotice
|
||||
if event.GetType() != protocol.EventTypeNotice {
|
||||
return false
|
||||
}
|
||||
// 如果没有指定类型,匹配所有通知事件
|
||||
if len(detailTypes) == 0 {
|
||||
return true
|
||||
}
|
||||
// 检查 detail_type 是否在指定列表中
|
||||
eventDetailType := event.GetDetailType()
|
||||
for _, dt := range detailTypes {
|
||||
if dt == eventDetailType {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
},
|
||||
priority: 100,
|
||||
}
|
||||
}
|
||||
|
||||
// OnRequest 匹配请求事件
|
||||
func OnRequest() *HandlerBuilder {
|
||||
// 用法:
|
||||
//
|
||||
// OnRequest() - 匹配所有请求事件
|
||||
// OnRequest("friend") - 匹配好友请求事件
|
||||
// OnRequest("friend", "group") - 匹配好友或群请求事件
|
||||
func OnRequest(detailTypes ...string) *HandlerBuilder {
|
||||
return &HandlerBuilder{
|
||||
matchFunc: func(event protocol.Event) bool {
|
||||
return event.GetType() == protocol.EventTypeRequest
|
||||
if event.GetType() != protocol.EventTypeRequest {
|
||||
return false
|
||||
}
|
||||
// 如果没有指定类型,匹配所有请求事件
|
||||
if len(detailTypes) == 0 {
|
||||
return true
|
||||
}
|
||||
// 检查 detail_type 是否在指定列表中
|
||||
eventDetailType := event.GetDetailType()
|
||||
for _, dt := range detailTypes {
|
||||
if dt == eventDetailType {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
},
|
||||
priority: 100,
|
||||
}
|
||||
}
|
||||
|
||||
// OnEvent 匹配指定类型的事件(可传一个或多个 EventType)
|
||||
// 用法:
|
||||
//
|
||||
// OnEvent() - 匹配所有事件
|
||||
// OnEvent(protocol.EventTypeMessage) - 匹配消息事件
|
||||
// OnEvent(protocol.EventTypeMessage, protocol.EventTypeNotice) - 匹配消息和通知事件
|
||||
func OnEvent(eventTypes ...protocol.EventType) *HandlerBuilder {
|
||||
return &HandlerBuilder{
|
||||
matchFunc: func(event protocol.Event) bool {
|
||||
if len(eventTypes) == 0 {
|
||||
return true // 不传参数时匹配所有事件
|
||||
}
|
||||
// 检查事件类型是否在指定列表中
|
||||
for _, et := range eventTypes {
|
||||
if event.GetType() == et {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
},
|
||||
priority: 100,
|
||||
}
|
||||
@@ -273,8 +341,13 @@ func On(matchFunc func(protocol.Event) bool) *HandlerBuilder {
|
||||
}
|
||||
}
|
||||
|
||||
// OnCommand 匹配命令(以指定前缀开头的消息)
|
||||
func OnCommand(prefix string) *HandlerBuilder {
|
||||
// OnCommand 匹配命令
|
||||
// 用法:
|
||||
//
|
||||
// OnCommand("/help") - 匹配 /help 命令(前缀为 /,命令为 help)
|
||||
// OnCommand("/", "help") - 匹配以 / 开头且命令为 help 的消息
|
||||
// OnCommand("/", "help", "h") - 匹配以 / 开头且命令为 help 或 h 的消息
|
||||
func OnCommand(prefix string, commands ...string) *HandlerBuilder {
|
||||
return &HandlerBuilder{
|
||||
matchFunc: func(event protocol.Event) bool {
|
||||
if event.GetType() != protocol.EventTypeMessage {
|
||||
@@ -285,9 +358,35 @@ func OnCommand(prefix string) *HandlerBuilder {
|
||||
if !ok {
|
||||
return false
|
||||
}
|
||||
// 检查是否以命令前缀开头
|
||||
if len(rawMessage) > 0 && len(prefix) > 0 {
|
||||
return len(rawMessage) >= len(prefix) && rawMessage[:len(prefix)] == prefix
|
||||
|
||||
// 检查是否以前缀开头
|
||||
if len(rawMessage) < len(prefix) || rawMessage[:len(prefix)] != prefix {
|
||||
return false
|
||||
}
|
||||
|
||||
// 如果没有指定具体命令,匹配所有以该前缀开头的消息
|
||||
if len(commands) == 0 {
|
||||
return true
|
||||
}
|
||||
|
||||
// 提取命令部分(去除前缀和空格)
|
||||
cmdText := strings.TrimSpace(rawMessage[len(prefix):])
|
||||
if cmdText == "" {
|
||||
return false
|
||||
}
|
||||
|
||||
// 获取第一个单词作为命令
|
||||
parts := strings.Fields(cmdText)
|
||||
if len(parts) == 0 {
|
||||
return false
|
||||
}
|
||||
cmd := parts[0]
|
||||
|
||||
// 检查是否匹配指定的命令
|
||||
for _, c := range commands {
|
||||
if cmd == c {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
},
|
||||
@@ -364,12 +463,56 @@ func contains(s, substr string) bool {
|
||||
return false
|
||||
}
|
||||
|
||||
// OnFullMatch 完全匹配文本
|
||||
func OnFullMatch(text string) *HandlerBuilder {
|
||||
return &HandlerBuilder{
|
||||
matchFunc: func(event protocol.Event) bool {
|
||||
if event.GetType() != protocol.EventTypeMessage {
|
||||
return false
|
||||
}
|
||||
data := event.GetData()
|
||||
rawMessage, ok := data["raw_message"].(string)
|
||||
if !ok {
|
||||
return false
|
||||
}
|
||||
return rawMessage == text
|
||||
},
|
||||
priority: 100,
|
||||
}
|
||||
}
|
||||
|
||||
// OnDetailType 匹配指定 detail_type 的事件
|
||||
func OnDetailType(detailType string) *HandlerBuilder {
|
||||
return &HandlerBuilder{
|
||||
matchFunc: func(event protocol.Event) bool {
|
||||
return event.GetDetailType() == detailType
|
||||
},
|
||||
priority: 100,
|
||||
}
|
||||
}
|
||||
|
||||
// OnSubType 匹配指定 sub_type 的事件
|
||||
func OnSubType(subType string) *HandlerBuilder {
|
||||
return &HandlerBuilder{
|
||||
matchFunc: func(event protocol.Event) bool {
|
||||
return event.GetSubType() == subType
|
||||
},
|
||||
priority: 100,
|
||||
}
|
||||
}
|
||||
|
||||
// Priority 设置优先级
|
||||
func (b *HandlerBuilder) Priority(priority int) *HandlerBuilder {
|
||||
b.priority = priority
|
||||
return b
|
||||
}
|
||||
|
||||
// Use 添加中间件(链式调用)
|
||||
func (b *HandlerBuilder) Use(middleware HandlerMiddleware) *HandlerBuilder {
|
||||
b.middlewares = append(b.middlewares, middleware)
|
||||
return b
|
||||
}
|
||||
|
||||
// Handle 注册处理函数(在 init 中调用)
|
||||
func (b *HandlerBuilder) Handle(handleFunc HandlerFunc) {
|
||||
globalHandlerMu.Lock()
|
||||
@@ -379,6 +522,16 @@ func (b *HandlerBuilder) Handle(handleFunc HandlerFunc) {
|
||||
globalHandlerRegistry = append(globalHandlerRegistry, b)
|
||||
}
|
||||
|
||||
// applyMiddlewares 应用所有中间件
|
||||
func (b *HandlerBuilder) applyMiddlewares(event protocol.Event) bool {
|
||||
for _, middleware := range b.middlewares {
|
||||
if !middleware(event) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// generateHandlerName 生成处理器名称
|
||||
var handlerCounter int64
|
||||
|
||||
@@ -406,11 +559,21 @@ func LoadAllHandlers(botManager *protocol.BotManager, logger *zap.Logger) []prot
|
||||
return builder.handleFunc(ctx, event, botManager, logger)
|
||||
}
|
||||
|
||||
// 创建包装的匹配函数,应用中间件
|
||||
matchFunc := func(event protocol.Event) bool {
|
||||
// 先检查基础匹配
|
||||
if builder.matchFunc != nil && !builder.matchFunc(event) {
|
||||
return false
|
||||
}
|
||||
// 再应用中间件
|
||||
return builder.applyMiddlewares(event)
|
||||
}
|
||||
|
||||
handler := &simplePlugin{
|
||||
name: pluginName,
|
||||
description: "Handler registered via OnXXX().Handle()",
|
||||
priority: builder.priority,
|
||||
matchFunc: builder.matchFunc,
|
||||
matchFunc: matchFunc,
|
||||
handleFunc: handleFunc,
|
||||
}
|
||||
|
||||
@@ -419,3 +582,129 @@ func LoadAllHandlers(botManager *protocol.BotManager, logger *zap.Logger) []prot
|
||||
|
||||
return handlers
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// 常用中间件(类似 NoneBot 风格)
|
||||
// ============================================================================
|
||||
|
||||
// OnlyToMe 只响应@机器人的消息(群聊中)
|
||||
func OnlyToMe() HandlerMiddleware {
|
||||
return func(event protocol.Event) bool {
|
||||
// 只对群消息生效
|
||||
if event.GetType() != protocol.EventTypeMessage || event.GetDetailType() != "group" {
|
||||
return true // 非群消息不检查,让其他中间件处理
|
||||
}
|
||||
|
||||
data := event.GetData()
|
||||
selfID := event.GetSelfID()
|
||||
|
||||
// 检查消息段中是否包含@机器人的消息
|
||||
if segments, ok := data["message_segments"].([]interface{}); ok {
|
||||
for _, seg := range segments {
|
||||
if segMap, ok := seg.(map[string]interface{}); ok {
|
||||
segType, _ := segMap["type"].(string)
|
||||
if segType == "at" || segType == "mention" {
|
||||
segData, _ := segMap["data"].(map[string]interface{})
|
||||
// 检查是否@了机器人
|
||||
if userID, ok := segData["user_id"]; ok {
|
||||
if userIDStr := fmt.Sprintf("%v", userID); userIDStr == selfID {
|
||||
return true
|
||||
}
|
||||
}
|
||||
if qq, ok := segData["qq"]; ok {
|
||||
if qqStr := fmt.Sprintf("%v", qq); qqStr == selfID {
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 检查 raw_message 中是否包含@机器人的信息(兼容性检查)
|
||||
if rawMessage, ok := data["raw_message"].(string); ok {
|
||||
// 简单的检查:消息是否以 @机器人 开头
|
||||
// 注意:这里需要根据实际协议调整
|
||||
if strings.Contains(rawMessage, fmt.Sprintf("[CQ:at,qq=%s]", selfID)) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
// OnlyPrivate 只在私聊中响应
|
||||
func OnlyPrivate() HandlerMiddleware {
|
||||
return func(event protocol.Event) bool {
|
||||
return event.GetType() == protocol.EventTypeMessage && event.GetDetailType() == "private"
|
||||
}
|
||||
}
|
||||
|
||||
// OnlyGroup 只在群聊中响应(消息事件)或群相关事件(通知/请求事件)
|
||||
func OnlyGroup() HandlerMiddleware {
|
||||
return func(event protocol.Event) bool {
|
||||
// 消息事件:检查 detail_type
|
||||
if event.GetType() == protocol.EventTypeMessage {
|
||||
return event.GetDetailType() == "group"
|
||||
}
|
||||
// 通知/请求事件:检查是否有 group_id
|
||||
data := event.GetData()
|
||||
_, hasGroupID := data["group_id"]
|
||||
return hasGroupID
|
||||
}
|
||||
}
|
||||
|
||||
// OnlySuperuser 只允许超级用户(需要从配置或数据中获取)
|
||||
func OnlySuperuser(superusers []string) HandlerMiddleware {
|
||||
return func(event protocol.Event) bool {
|
||||
data := event.GetData()
|
||||
userID, ok := data["user_id"]
|
||||
if !ok {
|
||||
return false
|
||||
}
|
||||
|
||||
userIDStr := fmt.Sprintf("%v", userID)
|
||||
for _, su := range superusers {
|
||||
if su == userIDStr {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
// BlockPrivate 阻止私聊消息
|
||||
func BlockPrivate() HandlerMiddleware {
|
||||
return func(event protocol.Event) bool {
|
||||
return !(event.GetType() == protocol.EventTypeMessage && event.GetDetailType() == "private")
|
||||
}
|
||||
}
|
||||
|
||||
// BlockGroup 阻止群聊消息
|
||||
func BlockGroup() HandlerMiddleware {
|
||||
return func(event protocol.Event) bool {
|
||||
// 消息事件:检查 detail_type
|
||||
if event.GetType() == protocol.EventTypeMessage {
|
||||
return event.GetDetailType() != "group"
|
||||
}
|
||||
// 通知/请求事件:检查是否有 group_id
|
||||
data := event.GetData()
|
||||
_, hasGroupID := data["group_id"]
|
||||
return !hasGroupID
|
||||
}
|
||||
}
|
||||
|
||||
// OnlyDetailType 只匹配指定的 detail_type
|
||||
func OnlyDetailType(detailType string) HandlerMiddleware {
|
||||
return func(event protocol.Event) bool {
|
||||
return event.GetDetailType() == detailType
|
||||
}
|
||||
}
|
||||
|
||||
// OnlySubType 只匹配指定的 sub_type
|
||||
func OnlySubType(subType string) HandlerMiddleware {
|
||||
return func(event protocol.Event) bool {
|
||||
return event.GetSubType() == subType
|
||||
}
|
||||
}
|
||||
|
||||
631
internal/engine/scheduler.go
Normal file
631
internal/engine/scheduler.go
Normal file
@@ -0,0 +1,631 @@
|
||||
package engine
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"github.com/robfig/cron/v3"
|
||||
"go.uber.org/zap"
|
||||
)
|
||||
|
||||
// Job 定时任务接口
|
||||
type Job interface {
|
||||
// ID 返回任务唯一标识
|
||||
ID() string
|
||||
// Start 启动任务
|
||||
Start(ctx context.Context) error
|
||||
// Stop 停止任务
|
||||
Stop() error
|
||||
// IsRunning 检查任务是否正在运行
|
||||
IsRunning() bool
|
||||
// NextRun 返回下次执行时间
|
||||
NextRun() time.Time
|
||||
}
|
||||
|
||||
// JobFunc 任务执行函数类型
|
||||
type JobFunc func(ctx context.Context) error
|
||||
|
||||
// Scheduler 定时任务调度器
|
||||
type Scheduler struct {
|
||||
jobs map[string]Job
|
||||
mu sync.RWMutex
|
||||
logger *zap.Logger
|
||||
ctx context.Context
|
||||
cancel context.CancelFunc
|
||||
wg sync.WaitGroup
|
||||
running int32
|
||||
}
|
||||
|
||||
// NewScheduler 创建新的调度器
|
||||
func NewScheduler(logger *zap.Logger) *Scheduler {
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
return &Scheduler{
|
||||
jobs: make(map[string]Job),
|
||||
logger: logger.Named("scheduler"),
|
||||
ctx: ctx,
|
||||
cancel: cancel,
|
||||
}
|
||||
}
|
||||
|
||||
// Start 启动调度器
|
||||
func (s *Scheduler) Start() error {
|
||||
if !atomic.CompareAndSwapInt32(&s.running, 0, 1) {
|
||||
return fmt.Errorf("scheduler is already running")
|
||||
}
|
||||
|
||||
s.mu.RLock()
|
||||
defer s.mu.RUnlock()
|
||||
|
||||
// 启动所有任务
|
||||
for id, job := range s.jobs {
|
||||
if err := job.Start(s.ctx); err != nil {
|
||||
s.logger.Error("Failed to start job",
|
||||
zap.String("job_id", id),
|
||||
zap.Error(err))
|
||||
continue
|
||||
}
|
||||
s.logger.Info("Job started", zap.String("job_id", id))
|
||||
}
|
||||
|
||||
s.logger.Info("Scheduler started", zap.Int("job_count", len(s.jobs)))
|
||||
return nil
|
||||
}
|
||||
|
||||
// Stop 停止调度器
|
||||
func (s *Scheduler) Stop() error {
|
||||
if !atomic.CompareAndSwapInt32(&s.running, 1, 0) {
|
||||
return fmt.Errorf("scheduler is not running")
|
||||
}
|
||||
|
||||
s.cancel()
|
||||
|
||||
s.mu.RLock()
|
||||
defer s.mu.RUnlock()
|
||||
|
||||
// 停止所有任务
|
||||
for id, job := range s.jobs {
|
||||
if err := job.Stop(); err != nil {
|
||||
s.logger.Error("Failed to stop job",
|
||||
zap.String("job_id", id),
|
||||
zap.Error(err))
|
||||
continue
|
||||
}
|
||||
s.logger.Info("Job stopped", zap.String("job_id", id))
|
||||
}
|
||||
|
||||
s.wg.Wait()
|
||||
s.logger.Info("Scheduler stopped")
|
||||
return nil
|
||||
}
|
||||
|
||||
// AddJob 添加任务
|
||||
func (s *Scheduler) AddJob(job Job) error {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
|
||||
id := job.ID()
|
||||
if _, exists := s.jobs[id]; exists {
|
||||
return fmt.Errorf("job with id %s already exists", id)
|
||||
}
|
||||
|
||||
s.jobs[id] = job
|
||||
|
||||
// 如果调度器正在运行,立即启动任务
|
||||
if atomic.LoadInt32(&s.running) == 1 {
|
||||
if err := job.Start(s.ctx); err != nil {
|
||||
delete(s.jobs, id)
|
||||
return fmt.Errorf("failed to start job: %w", err)
|
||||
}
|
||||
s.logger.Info("Job added and started", zap.String("job_id", id))
|
||||
} else {
|
||||
s.logger.Info("Job added", zap.String("job_id", id))
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// RemoveJob 移除任务
|
||||
func (s *Scheduler) RemoveJob(id string) error {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
|
||||
job, exists := s.jobs[id]
|
||||
if !exists {
|
||||
return fmt.Errorf("job with id %s not found", id)
|
||||
}
|
||||
|
||||
if err := job.Stop(); err != nil {
|
||||
s.logger.Error("Failed to stop job during removal",
|
||||
zap.String("job_id", id),
|
||||
zap.Error(err))
|
||||
}
|
||||
|
||||
delete(s.jobs, id)
|
||||
s.logger.Info("Job removed", zap.String("job_id", id))
|
||||
return nil
|
||||
}
|
||||
|
||||
// GetJob 获取任务
|
||||
func (s *Scheduler) GetJob(id string) (Job, bool) {
|
||||
s.mu.RLock()
|
||||
defer s.mu.RUnlock()
|
||||
job, exists := s.jobs[id]
|
||||
return job, exists
|
||||
}
|
||||
|
||||
// GetAllJobs 获取所有任务
|
||||
func (s *Scheduler) GetAllJobs() map[string]Job {
|
||||
s.mu.RLock()
|
||||
defer s.mu.RUnlock()
|
||||
|
||||
result := make(map[string]Job, len(s.jobs))
|
||||
for id, job := range s.jobs {
|
||||
result[id] = job
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
// IsRunning 检查调度器是否正在运行
|
||||
func (s *Scheduler) IsRunning() bool {
|
||||
return atomic.LoadInt32(&s.running) == 1
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// Job 实现
|
||||
// ============================================================================
|
||||
|
||||
// CronJob 基于 Cron 表达式的任务
|
||||
type CronJob struct {
|
||||
id string
|
||||
spec string
|
||||
handler JobFunc
|
||||
cron *cron.Cron
|
||||
logger *zap.Logger
|
||||
running int32
|
||||
nextRun time.Time
|
||||
mu sync.RWMutex
|
||||
}
|
||||
|
||||
// NewCronJob 创建 Cron 任务
|
||||
func NewCronJob(id, spec string, handler JobFunc, logger *zap.Logger) (*CronJob, error) {
|
||||
parser := cron.NewParser(cron.Second | cron.Minute | cron.Hour | cron.Dom | cron.Month | cron.Dow | cron.Descriptor)
|
||||
c := cron.New(cron.WithParser(parser), cron.WithChain(cron.Recover(cron.DefaultLogger)))
|
||||
|
||||
job := &CronJob{
|
||||
id: id,
|
||||
spec: spec,
|
||||
handler: handler,
|
||||
cron: c,
|
||||
logger: logger.Named("cron-job").With(zap.String("job_id", id)),
|
||||
}
|
||||
|
||||
// 添加任务到 cron
|
||||
_, err := c.AddFunc(spec, func() {
|
||||
ctx := context.Background()
|
||||
if err := handler(ctx); err != nil {
|
||||
job.logger.Error("Cron job execution failed", zap.Error(err))
|
||||
}
|
||||
// 更新下次执行时间
|
||||
entries := c.Entries()
|
||||
job.mu.Lock()
|
||||
if len(entries) > 0 {
|
||||
// 找到最近的执行时间
|
||||
next := entries[0].Next
|
||||
for _, entry := range entries {
|
||||
if entry.Next.Before(next) {
|
||||
next = entry.Next
|
||||
}
|
||||
}
|
||||
job.nextRun = next
|
||||
}
|
||||
job.mu.Unlock()
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("invalid cron spec: %w", err)
|
||||
}
|
||||
|
||||
// 计算初始下次执行时间(需要先启动 cron 才能计算)
|
||||
// 这里先设置为零值,在 Start 时再计算
|
||||
job.mu.Lock()
|
||||
job.nextRun = time.Time{}
|
||||
job.mu.Unlock()
|
||||
|
||||
return job, nil
|
||||
}
|
||||
|
||||
func (j *CronJob) ID() string {
|
||||
return j.id
|
||||
}
|
||||
|
||||
func (j *CronJob) Start(ctx context.Context) error {
|
||||
if !atomic.CompareAndSwapInt32(&j.running, 0, 1) {
|
||||
return fmt.Errorf("job is already running")
|
||||
}
|
||||
|
||||
j.cron.Start()
|
||||
j.logger.Info("Cron job started", zap.String("spec", j.spec))
|
||||
|
||||
// 更新下次执行时间
|
||||
entries := j.cron.Entries()
|
||||
if len(entries) > 0 {
|
||||
j.mu.Lock()
|
||||
// 找到最近的执行时间
|
||||
next := entries[0].Next
|
||||
for _, entry := range entries {
|
||||
if entry.Next.Before(next) {
|
||||
next = entry.Next
|
||||
}
|
||||
}
|
||||
j.nextRun = next
|
||||
j.mu.Unlock()
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (j *CronJob) Stop() error {
|
||||
if !atomic.CompareAndSwapInt32(&j.running, 1, 0) {
|
||||
return fmt.Errorf("job is not running")
|
||||
}
|
||||
|
||||
ctx := j.cron.Stop()
|
||||
<-ctx.Done()
|
||||
j.logger.Info("Cron job stopped")
|
||||
return nil
|
||||
}
|
||||
|
||||
func (j *CronJob) IsRunning() bool {
|
||||
return atomic.LoadInt32(&j.running) == 1
|
||||
}
|
||||
|
||||
func (j *CronJob) NextRun() time.Time {
|
||||
j.mu.RLock()
|
||||
defer j.mu.RUnlock()
|
||||
return j.nextRun
|
||||
}
|
||||
|
||||
// IntervalJob 固定间隔的任务
|
||||
type IntervalJob struct {
|
||||
id string
|
||||
interval time.Duration
|
||||
handler JobFunc
|
||||
logger *zap.Logger
|
||||
running int32
|
||||
nextRun time.Time
|
||||
mu sync.RWMutex
|
||||
ticker *time.Ticker
|
||||
ctx context.Context
|
||||
cancel context.CancelFunc
|
||||
wg sync.WaitGroup
|
||||
}
|
||||
|
||||
// NewIntervalJob 创建固定间隔任务
|
||||
func NewIntervalJob(id string, interval time.Duration, handler JobFunc, logger *zap.Logger) *IntervalJob {
|
||||
return &IntervalJob{
|
||||
id: id,
|
||||
interval: interval,
|
||||
handler: handler,
|
||||
logger: logger.Named("interval-job").With(zap.String("job_id", id)),
|
||||
}
|
||||
}
|
||||
|
||||
func (j *IntervalJob) ID() string {
|
||||
return j.id
|
||||
}
|
||||
|
||||
func (j *IntervalJob) Start(ctx context.Context) error {
|
||||
if !atomic.CompareAndSwapInt32(&j.running, 0, 1) {
|
||||
return fmt.Errorf("job is already running")
|
||||
}
|
||||
|
||||
j.ctx, j.cancel = context.WithCancel(ctx)
|
||||
j.ticker = time.NewTicker(j.interval)
|
||||
|
||||
j.mu.Lock()
|
||||
j.nextRun = time.Now().Add(j.interval)
|
||||
j.mu.Unlock()
|
||||
|
||||
j.wg.Add(1)
|
||||
go j.run()
|
||||
|
||||
j.logger.Info("Interval job started", zap.Duration("interval", j.interval))
|
||||
return nil
|
||||
}
|
||||
|
||||
func (j *IntervalJob) run() {
|
||||
defer j.wg.Done()
|
||||
|
||||
// 立即执行一次(可选,根据需求调整)
|
||||
// if err := j.handler(j.ctx); err != nil {
|
||||
// j.logger.Error("Interval job execution failed", zap.Error(err))
|
||||
// }
|
||||
|
||||
for {
|
||||
select {
|
||||
case <-j.ticker.C:
|
||||
j.mu.Lock()
|
||||
j.nextRun = time.Now().Add(j.interval)
|
||||
j.mu.Unlock()
|
||||
|
||||
if err := j.handler(j.ctx); err != nil {
|
||||
j.logger.Error("Interval job execution failed", zap.Error(err))
|
||||
}
|
||||
case <-j.ctx.Done():
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (j *IntervalJob) Stop() error {
|
||||
if !atomic.CompareAndSwapInt32(&j.running, 1, 0) {
|
||||
return fmt.Errorf("job is not running")
|
||||
}
|
||||
|
||||
if j.cancel != nil {
|
||||
j.cancel()
|
||||
}
|
||||
if j.ticker != nil {
|
||||
j.ticker.Stop()
|
||||
}
|
||||
j.wg.Wait()
|
||||
|
||||
j.logger.Info("Interval job stopped")
|
||||
return nil
|
||||
}
|
||||
|
||||
func (j *IntervalJob) IsRunning() bool {
|
||||
return atomic.LoadInt32(&j.running) == 1
|
||||
}
|
||||
|
||||
func (j *IntervalJob) NextRun() time.Time {
|
||||
j.mu.RLock()
|
||||
defer j.mu.RUnlock()
|
||||
return j.nextRun
|
||||
}
|
||||
|
||||
// OnceJob 单次延迟执行的任务
|
||||
type OnceJob struct {
|
||||
id string
|
||||
delay time.Duration
|
||||
handler JobFunc
|
||||
logger *zap.Logger
|
||||
running int32
|
||||
nextRun time.Time
|
||||
mu sync.RWMutex
|
||||
timer *time.Timer
|
||||
ctx context.Context
|
||||
cancel context.CancelFunc
|
||||
wg sync.WaitGroup
|
||||
}
|
||||
|
||||
// NewOnceJob 创建单次延迟执行任务
|
||||
func NewOnceJob(id string, delay time.Duration, handler JobFunc, logger *zap.Logger) *OnceJob {
|
||||
return &OnceJob{
|
||||
id: id,
|
||||
delay: delay,
|
||||
handler: handler,
|
||||
logger: logger.Named("once-job").With(zap.String("job_id", id)),
|
||||
}
|
||||
}
|
||||
|
||||
func (j *OnceJob) ID() string {
|
||||
return j.id
|
||||
}
|
||||
|
||||
func (j *OnceJob) Start(ctx context.Context) error {
|
||||
if !atomic.CompareAndSwapInt32(&j.running, 0, 1) {
|
||||
return fmt.Errorf("job is already running")
|
||||
}
|
||||
|
||||
j.ctx, j.cancel = context.WithCancel(ctx)
|
||||
j.timer = time.NewTimer(j.delay)
|
||||
|
||||
j.mu.Lock()
|
||||
j.nextRun = time.Now().Add(j.delay)
|
||||
j.mu.Unlock()
|
||||
|
||||
j.wg.Add(1)
|
||||
go j.run()
|
||||
|
||||
j.logger.Info("Once job started", zap.Duration("delay", j.delay))
|
||||
return nil
|
||||
}
|
||||
|
||||
func (j *OnceJob) run() {
|
||||
defer j.wg.Done()
|
||||
|
||||
select {
|
||||
case <-j.timer.C:
|
||||
if err := j.handler(j.ctx); err != nil {
|
||||
j.logger.Error("Once job execution failed", zap.Error(err))
|
||||
}
|
||||
atomic.StoreInt32(&j.running, 0)
|
||||
case <-j.ctx.Done():
|
||||
if !j.timer.Stop() {
|
||||
<-j.timer.C
|
||||
}
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
func (j *OnceJob) Stop() error {
|
||||
if !atomic.CompareAndSwapInt32(&j.running, 1, 0) {
|
||||
return fmt.Errorf("job is not running")
|
||||
}
|
||||
|
||||
if j.cancel != nil {
|
||||
j.cancel()
|
||||
}
|
||||
if j.timer != nil {
|
||||
if !j.timer.Stop() {
|
||||
<-j.timer.C
|
||||
}
|
||||
}
|
||||
j.wg.Wait()
|
||||
|
||||
j.logger.Info("Once job stopped")
|
||||
return nil
|
||||
}
|
||||
|
||||
func (j *OnceJob) IsRunning() bool {
|
||||
return atomic.LoadInt32(&j.running) == 1
|
||||
}
|
||||
|
||||
func (j *OnceJob) NextRun() time.Time {
|
||||
j.mu.RLock()
|
||||
defer j.mu.RUnlock()
|
||||
return j.nextRun
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// 全局调度器 API(链式风格,延迟注册)
|
||||
// ============================================================================
|
||||
|
||||
var (
|
||||
globalJobRegistry = make([]JobBuilder, 0)
|
||||
globalJobMu sync.RWMutex
|
||||
jobCounter int64
|
||||
)
|
||||
|
||||
// JobBuilder 任务构建器接口(延迟注册)
|
||||
type JobBuilder interface {
|
||||
// Build 构建任务实例(由依赖注入系统调用)
|
||||
Build(logger *zap.Logger) (Job, error)
|
||||
}
|
||||
|
||||
// generateJobID 生成任务 ID
|
||||
func generateJobID(prefix string) string {
|
||||
counter := atomic.AddInt64(&jobCounter, 1)
|
||||
return fmt.Sprintf("%s_%d", prefix, counter)
|
||||
}
|
||||
|
||||
// CronJobBuilder Cron 任务构建器
|
||||
type CronJobBuilder struct {
|
||||
id string
|
||||
spec string
|
||||
handler JobFunc
|
||||
}
|
||||
|
||||
// Cron 创建 Cron 任务构建器(在 init 函数中调用)
|
||||
func Cron(spec string) *CronJobBuilder {
|
||||
return &CronJobBuilder{
|
||||
id: generateJobID("cron"),
|
||||
spec: spec,
|
||||
}
|
||||
}
|
||||
|
||||
// Handle 设置处理函数并注册到全局注册表(延迟注册)
|
||||
func (b *CronJobBuilder) Handle(handler JobFunc) {
|
||||
b.handler = handler
|
||||
if b.handler == nil {
|
||||
panic("scheduler: handler cannot be nil")
|
||||
}
|
||||
|
||||
globalJobMu.Lock()
|
||||
defer globalJobMu.Unlock()
|
||||
globalJobRegistry = append(globalJobRegistry, b)
|
||||
}
|
||||
|
||||
// Build 构建 Cron 任务
|
||||
func (b *CronJobBuilder) Build(logger *zap.Logger) (Job, error) {
|
||||
return NewCronJob(b.id, b.spec, b.handler, logger)
|
||||
}
|
||||
|
||||
// IntervalJobBuilder 固定间隔任务构建器
|
||||
type IntervalJobBuilder struct {
|
||||
id string
|
||||
interval time.Duration
|
||||
handler JobFunc
|
||||
}
|
||||
|
||||
// Interval 创建固定间隔任务构建器(在 init 函数中调用)
|
||||
func Interval(interval time.Duration) *IntervalJobBuilder {
|
||||
return &IntervalJobBuilder{
|
||||
id: generateJobID("interval"),
|
||||
interval: interval,
|
||||
}
|
||||
}
|
||||
|
||||
// Handle 设置处理函数并注册到全局注册表(延迟注册)
|
||||
func (b *IntervalJobBuilder) Handle(handler JobFunc) {
|
||||
b.handler = handler
|
||||
if b.handler == nil {
|
||||
panic("scheduler: handler cannot be nil")
|
||||
}
|
||||
|
||||
globalJobMu.Lock()
|
||||
defer globalJobMu.Unlock()
|
||||
globalJobRegistry = append(globalJobRegistry, b)
|
||||
}
|
||||
|
||||
// Build 构建固定间隔任务
|
||||
func (b *IntervalJobBuilder) Build(logger *zap.Logger) (Job, error) {
|
||||
return NewIntervalJob(b.id, b.interval, b.handler, logger), nil
|
||||
}
|
||||
|
||||
// OnceJobBuilder 单次延迟任务构建器
|
||||
type OnceJobBuilder struct {
|
||||
id string
|
||||
delay time.Duration
|
||||
handler JobFunc
|
||||
}
|
||||
|
||||
// Once 创建单次延迟任务构建器(在 init 函数中调用)
|
||||
func Once(delay time.Duration) *OnceJobBuilder {
|
||||
return &OnceJobBuilder{
|
||||
id: generateJobID("once"),
|
||||
delay: delay,
|
||||
}
|
||||
}
|
||||
|
||||
// Handle 设置处理函数并注册到全局注册表(延迟注册)
|
||||
func (b *OnceJobBuilder) Handle(handler JobFunc) {
|
||||
b.handler = handler
|
||||
if b.handler == nil {
|
||||
panic("scheduler: handler cannot be nil")
|
||||
}
|
||||
|
||||
globalJobMu.Lock()
|
||||
defer globalJobMu.Unlock()
|
||||
globalJobRegistry = append(globalJobRegistry, b)
|
||||
}
|
||||
|
||||
// Build 构建单次延迟任务
|
||||
func (b *OnceJobBuilder) Build(logger *zap.Logger) (Job, error) {
|
||||
return NewOnceJob(b.id, b.delay, b.handler, logger), nil
|
||||
}
|
||||
|
||||
// LoadAllJobs 加载所有已注册的任务(由依赖注入系统调用)
|
||||
func LoadAllJobs(scheduler *Scheduler, logger *zap.Logger) error {
|
||||
globalJobMu.RLock()
|
||||
defer globalJobMu.RUnlock()
|
||||
|
||||
for i, builder := range globalJobRegistry {
|
||||
job, err := builder.Build(logger)
|
||||
if err != nil {
|
||||
logger.Error("Failed to build job",
|
||||
zap.Int("index", i),
|
||||
zap.Error(err))
|
||||
continue
|
||||
}
|
||||
|
||||
if err := scheduler.AddJob(job); err != nil {
|
||||
logger.Error("Failed to add job to scheduler",
|
||||
zap.String("job_id", job.ID()),
|
||||
zap.Error(err))
|
||||
continue
|
||||
}
|
||||
|
||||
logger.Debug("Job loaded",
|
||||
zap.String("job_id", job.ID()))
|
||||
}
|
||||
|
||||
logger.Info("All scheduled jobs loaded",
|
||||
zap.Int("job_count", len(globalJobRegistry)))
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -2,6 +2,7 @@ package echo
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
|
||||
"cellbot/internal/engine"
|
||||
"cellbot/internal/protocol"
|
||||
@@ -10,55 +11,27 @@ import (
|
||||
)
|
||||
|
||||
func init() {
|
||||
// 在 init 函数中注册多个处理函数(类似 ZeroBot 风格)
|
||||
|
||||
// 处理私聊消息
|
||||
engine.OnPrivateMessage().
|
||||
// 注册 /echo 命令
|
||||
engine.OnCommand("/echo").
|
||||
Handle(func(ctx context.Context, event protocol.Event, botManager *protocol.BotManager, logger *zap.Logger) error {
|
||||
// 获取消息内容
|
||||
data := event.GetData()
|
||||
message, ok := data["message"]
|
||||
rawMessage, ok := data["raw_message"].(string)
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
|
||||
userID, ok := data["user_id"]
|
||||
if !ok {
|
||||
return nil
|
||||
// 解析命令参数(/echo 后面的内容)
|
||||
parts := strings.Fields(rawMessage)
|
||||
if len(parts) < 2 {
|
||||
// 如果没有参数,返回提示
|
||||
return event.ReplyText(ctx, botManager, logger, "用法: /echo <消息内容>")
|
||||
}
|
||||
|
||||
// 获取 bot 实例
|
||||
selfID := event.GetSelfID()
|
||||
bot, ok := botManager.Get(selfID)
|
||||
if !ok {
|
||||
bots := botManager.GetAll()
|
||||
if len(bots) == 0 {
|
||||
logger.Error("No bot instance available")
|
||||
return nil
|
||||
}
|
||||
bot = bots[0]
|
||||
}
|
||||
// 获取要回显的内容
|
||||
echoContent := strings.Join(parts[1:], " ")
|
||||
|
||||
// 发送回复
|
||||
action := &protocol.BaseAction{
|
||||
Type: protocol.ActionTypeSendPrivateMessage,
|
||||
Params: map[string]interface{}{
|
||||
"user_id": userID,
|
||||
"message": message,
|
||||
},
|
||||
}
|
||||
|
||||
_, err := bot.SendAction(ctx, action)
|
||||
if err != nil {
|
||||
logger.Error("Failed to send reply", zap.Error(err))
|
||||
return err
|
||||
}
|
||||
|
||||
logger.Info("Echo reply sent", zap.Any("user_id", userID))
|
||||
return nil
|
||||
// 使用 ReplyText 发送回复
|
||||
return event.ReplyText(ctx, botManager, logger, echoContent)
|
||||
})
|
||||
|
||||
// 可以继续注册更多处理函数
|
||||
// engine.OnGroupMessage().Handle(...)
|
||||
// engine.OnCommand("help").Handle(...)
|
||||
}
|
||||
|
||||
375
internal/plugins/mcstatus/mcstatus.go
Normal file
375
internal/plugins/mcstatus/mcstatus.go
Normal file
@@ -0,0 +1,375 @@
|
||||
package mcstatus
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"cellbot/internal/database"
|
||||
"cellbot/internal/engine"
|
||||
"cellbot/internal/protocol"
|
||||
"cellbot/pkg/utils"
|
||||
|
||||
"go.uber.org/zap"
|
||||
)
|
||||
|
||||
// ServerBind 服务器绑定模型
|
||||
type ServerBind struct {
|
||||
ID string `gorm:"primaryKey"` // group_id
|
||||
ServerIP string `gorm:"not null"` // 服务器IP
|
||||
}
|
||||
|
||||
// TableName 指定表名(基础表名,实际使用时需要添加 botID 前缀)
|
||||
func (ServerBind) TableName() string {
|
||||
return "mc_server_binds"
|
||||
}
|
||||
|
||||
var dbService database.Database
|
||||
|
||||
func init() {
|
||||
// 注册命令(数据库将在依赖注入时初始化)
|
||||
engine.OnCommand("/mcs").
|
||||
Priority(100).
|
||||
Handle(handleMCSCommand)
|
||||
|
||||
engine.OnCommand("/mcsBind").
|
||||
Priority(100).
|
||||
Handle(handleMCSBindCommand)
|
||||
}
|
||||
|
||||
// InitDatabase 初始化数据库(由依赖注入调用)
|
||||
func InitDatabase(database database.Database) error {
|
||||
dbService = database
|
||||
return nil
|
||||
}
|
||||
|
||||
// handleMCSCommand 处理 /mcs 命令
|
||||
func handleMCSCommand(ctx context.Context, event protocol.Event, botManager *protocol.BotManager, logger *zap.Logger) error {
|
||||
logger.Info("handleMCSCommand called",
|
||||
zap.String("self_id", event.GetSelfID()),
|
||||
zap.String("detail_type", event.GetDetailType()))
|
||||
|
||||
data := event.GetData()
|
||||
|
||||
// 获取原始消息内容
|
||||
rawMessage, ok := data["raw_message"].(string)
|
||||
if !ok {
|
||||
logger.Warn("raw_message not found in event data")
|
||||
return nil
|
||||
}
|
||||
|
||||
logger.Info("Processing /mcs command",
|
||||
zap.String("raw_message", rawMessage))
|
||||
|
||||
// 解析命令参数(/mcs 后面的内容)
|
||||
var serverIP string
|
||||
parts := strings.Fields(rawMessage)
|
||||
if len(parts) > 1 {
|
||||
serverIP = strings.Join(parts[1:], " ")
|
||||
}
|
||||
|
||||
// 如果没有提供 IP,尝试从群绑定或默认配置获取
|
||||
if serverIP == "" {
|
||||
groupID, _ := data["group_id"]
|
||||
botID := event.GetSelfID()
|
||||
if groupID != nil && dbService != nil && botID != "" {
|
||||
db, err := dbService.GetDB(botID)
|
||||
if err != nil {
|
||||
logger.Warn("Failed to get database for bot",
|
||||
zap.String("bot_id", botID),
|
||||
zap.Error(err))
|
||||
} else {
|
||||
var bind ServerBind
|
||||
tableName := database.GetTableName(botID, "mc_server_binds")
|
||||
if err := db.Table(tableName).Where("id = ?", fmt.Sprintf("%v", groupID)).First(&bind).Error; err != nil {
|
||||
logger.Debug("No server bind found for group",
|
||||
zap.String("bot_id", botID),
|
||||
zap.Any("group_id", groupID),
|
||||
zap.Error(err))
|
||||
} else {
|
||||
serverIP = bind.ServerIP
|
||||
}
|
||||
}
|
||||
}
|
||||
// 如果还是没有,使用默认值
|
||||
if serverIP == "" {
|
||||
serverIP = "mc.hypixel.net" // 默认服务器
|
||||
}
|
||||
}
|
||||
|
||||
// 解析服务器地址和端口
|
||||
host := serverIP
|
||||
port := 25565
|
||||
if strings.Contains(serverIP, ":") {
|
||||
parts := strings.Split(serverIP, ":")
|
||||
host = parts[0]
|
||||
fmt.Sscanf(parts[1], "%d", &port)
|
||||
}
|
||||
|
||||
logger.Info("Querying Minecraft server",
|
||||
zap.String("host", host),
|
||||
zap.Int("port", port))
|
||||
|
||||
// 查询服务器状态
|
||||
status, err := Ping(host, port, 10*time.Second)
|
||||
if err != nil {
|
||||
logger.Error("Failed to ping server", zap.Error(err))
|
||||
|
||||
// 使用 ReplyText 发送错误消息
|
||||
errorMsg := fmt.Sprintf("查询失败: %v", err)
|
||||
event.ReplyText(ctx, botManager, logger, errorMsg)
|
||||
return err
|
||||
}
|
||||
|
||||
// 构建 HTML 模板
|
||||
htmlTemplate := buildStatusHTML(status)
|
||||
|
||||
// 配置截图选项
|
||||
opts := &utils.ScreenshotOptions{
|
||||
Width: 1200,
|
||||
Height: 800,
|
||||
Timeout: 60 * time.Second,
|
||||
WaitTime: 3 * time.Second,
|
||||
FullPage: false,
|
||||
Quality: 90,
|
||||
Logger: logger,
|
||||
}
|
||||
|
||||
// 使用独立的 context 进行截图,避免受 dispatcher context 影响
|
||||
// 如果 dispatcher context 被取消,截图操作仍能完成
|
||||
screenshotCtx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
|
||||
defer cancel()
|
||||
|
||||
// 渲染并截图
|
||||
chain, err := utils.ScreenshotHTMLToMessageChain(screenshotCtx, htmlTemplate, opts)
|
||||
if err != nil {
|
||||
logger.Error("Failed to render status image", zap.Error(err))
|
||||
return err
|
||||
}
|
||||
|
||||
// 使用 Reply 发送图片
|
||||
err = event.Reply(ctx, botManager, logger, chain)
|
||||
if err != nil {
|
||||
logger.Error("Failed to send status image", zap.Error(err))
|
||||
return err
|
||||
}
|
||||
|
||||
logger.Info("Minecraft server status sent",
|
||||
zap.String("host", host),
|
||||
zap.Int("port", port))
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// handleMCSBindCommand 处理 /mcsBind 命令
|
||||
func handleMCSBindCommand(ctx context.Context, event protocol.Event, botManager *protocol.BotManager, logger *zap.Logger) error {
|
||||
data := event.GetData()
|
||||
|
||||
// 只允许群聊使用
|
||||
if event.GetDetailType() != "group" {
|
||||
return event.ReplyText(ctx, botManager, logger, "此命令只能在群聊中使用")
|
||||
}
|
||||
|
||||
// 获取原始消息内容
|
||||
rawMessage, ok := data["raw_message"].(string)
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
|
||||
// 解析命令参数(/mcsBind 后面的内容)
|
||||
parts := strings.Fields(rawMessage)
|
||||
if len(parts) < 2 {
|
||||
groupID, _ := data["group_id"]
|
||||
errorMsg := protocol.NewMessageChain(
|
||||
protocol.NewTextSegment("用法: /mcsBind <服务器IP>"),
|
||||
)
|
||||
|
||||
action := &protocol.BaseAction{
|
||||
Type: protocol.ActionTypeSendGroupMessage,
|
||||
Params: map[string]interface{}{
|
||||
"group_id": groupID,
|
||||
"message": errorMsg,
|
||||
},
|
||||
}
|
||||
|
||||
selfID := event.GetSelfID()
|
||||
bot, ok := botManager.Get(selfID)
|
||||
if !ok {
|
||||
bots := botManager.GetAll()
|
||||
if len(bots) > 0 {
|
||||
bot = bots[0]
|
||||
}
|
||||
}
|
||||
if bot != nil {
|
||||
bot.SendAction(ctx, action)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
serverIP := strings.Join(parts[1:], " ")
|
||||
groupID, _ := data["group_id"]
|
||||
groupIDStr := fmt.Sprintf("%v", groupID)
|
||||
botID := event.GetSelfID()
|
||||
|
||||
// 保存绑定到数据库
|
||||
if dbService != nil && botID != "" {
|
||||
db, err := dbService.GetDB(botID)
|
||||
if err == nil {
|
||||
// 自动迁移表(如果不存在)
|
||||
tableName := database.GetTableName(botID, "mc_server_binds")
|
||||
if err := db.Table(tableName).AutoMigrate(&ServerBind{}); err != nil {
|
||||
logger.Error("Failed to migrate table", zap.Error(err))
|
||||
} else {
|
||||
bind := ServerBind{
|
||||
ID: groupIDStr,
|
||||
ServerIP: serverIP,
|
||||
}
|
||||
// 使用 Save 方法,如果存在则更新,不存在则创建
|
||||
if err := db.Table(tableName).Save(&bind).Error; err != nil {
|
||||
logger.Error("Failed to save server bind", zap.Error(err))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 使用 ReplyText 发送确认消息
|
||||
successMsg := fmt.Sprintf("已绑定服务器 %s 到本群", serverIP)
|
||||
err := event.ReplyText(ctx, botManager, logger, successMsg)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
logger.Info("Minecraft server bound",
|
||||
zap.String("group_id", groupIDStr),
|
||||
zap.String("server_ip", serverIP))
|
||||
return nil
|
||||
}
|
||||
|
||||
// buildStatusHTML 构建服务器状态 HTML
|
||||
func buildStatusHTML(status *ServerStatus) string {
|
||||
iconHTML := ""
|
||||
if status.Favicon != "" {
|
||||
iconHTML = fmt.Sprintf(`<img src="data:image/png;base64,%s" alt="icon" style="width: 64px; height: 64px; border-radius: 8px;" />`, status.Favicon)
|
||||
}
|
||||
|
||||
return fmt.Sprintf(`
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<style>
|
||||
* {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
body {
|
||||
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
|
||||
background: linear-gradient(135deg, #2e3440 0%%, #434c5e 100%%);
|
||||
padding: 40px 20px;
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
align-items: center;
|
||||
min-height: 100vh;
|
||||
color: #cdd6f4;
|
||||
}
|
||||
.container {
|
||||
background: #2e3440;
|
||||
border-radius: 20px;
|
||||
padding: 40px;
|
||||
max-width: 800px;
|
||||
width: 100%%;
|
||||
box-shadow: 0 20px 60px rgba(0, 0, 0, 0.5);
|
||||
}
|
||||
.header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 20px;
|
||||
margin-bottom: 30px;
|
||||
}
|
||||
.icon {
|
||||
flex-shrink: 0;
|
||||
}
|
||||
.title {
|
||||
font-size: 28px;
|
||||
font-weight: bold;
|
||||
color: #cdd6f4;
|
||||
}
|
||||
.info-section {
|
||||
background: #434c5e;
|
||||
border-radius: 10px;
|
||||
padding: 20px;
|
||||
margin: 20px 0;
|
||||
}
|
||||
.info-item {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
padding: 10px 0;
|
||||
border-bottom: 1px solid #3b4252;
|
||||
}
|
||||
.info-item:last-child {
|
||||
border-bottom: none;
|
||||
}
|
||||
.info-label {
|
||||
font-weight: 600;
|
||||
color: #81a1c1;
|
||||
}
|
||||
.info-value {
|
||||
color: #cdd6f4;
|
||||
}
|
||||
.description {
|
||||
background: #3b4252;
|
||||
border-radius: 8px;
|
||||
padding: 15px;
|
||||
margin: 20px 0;
|
||||
color: #cdd6f4;
|
||||
font-size: 16px;
|
||||
}
|
||||
.footer {
|
||||
text-align: center;
|
||||
margin-top: 30px;
|
||||
color: #81a1c1;
|
||||
font-size: 14px;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="container">
|
||||
<div class="header">
|
||||
%s
|
||||
<div class="title">Minecraft 服务器状态</div>
|
||||
</div>
|
||||
|
||||
<div class="info-section">
|
||||
<div class="info-item">
|
||||
<span class="info-label">服务器地址:</span>
|
||||
<span class="info-value">%s</span>
|
||||
</div>
|
||||
<div class="info-item">
|
||||
<span class="info-label">延迟:</span>
|
||||
<span class="info-value">%d ms</span>
|
||||
</div>
|
||||
<div class="info-item">
|
||||
<span class="info-label">版本:</span>
|
||||
<span class="info-value">%s (协议 %d)</span>
|
||||
</div>
|
||||
<div class="info-item">
|
||||
<span class="info-label">在线人数:</span>
|
||||
<span class="info-value">%d / %d</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="description">
|
||||
<strong>服务器描述:</strong><br>
|
||||
%s
|
||||
</div>
|
||||
|
||||
<div class="footer">
|
||||
Generated by mc-server-status
|
||||
</div>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
`, iconHTML, fmt.Sprintf("%s:%d", status.Host, status.Port), status.Latency, status.Version.Name, status.Version.Protocol, status.Players.Online, status.Players.Max, status.Description)
|
||||
}
|
||||
141
internal/plugins/mcstatus/ping.go
Normal file
141
internal/plugins/mcstatus/ping.go
Normal file
@@ -0,0 +1,141 @@
|
||||
package mcstatus
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
mcnet "github.com/Tnze/go-mc/net"
|
||||
pk "github.com/Tnze/go-mc/net/packet"
|
||||
)
|
||||
|
||||
// ServerStatus 服务器状态信息
|
||||
type ServerStatus struct {
|
||||
Host string
|
||||
Port int
|
||||
Latency int64 // 延迟(毫秒)
|
||||
Version Version
|
||||
Players Players
|
||||
Description string // MOTD
|
||||
Favicon string // Base64 编码的图标
|
||||
}
|
||||
|
||||
// Version 版本信息
|
||||
type Version struct {
|
||||
Name string
|
||||
Protocol int
|
||||
}
|
||||
|
||||
// Players 玩家信息
|
||||
type Players struct {
|
||||
Online int
|
||||
Max int
|
||||
}
|
||||
|
||||
// Ping 查询 Minecraft 服务器状态
|
||||
func Ping(host string, port int, timeout time.Duration) (*ServerStatus, error) {
|
||||
// 连接服务器
|
||||
startTime := time.Now()
|
||||
conn, err := mcnet.DialMC(fmt.Sprintf("%s:%d", host, port))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to connect: %w", err)
|
||||
}
|
||||
defer conn.Close()
|
||||
|
||||
latency := time.Since(startTime).Milliseconds()
|
||||
|
||||
// 发送握手包
|
||||
handshake := pk.Marshal(
|
||||
0x00, // Handshake packet ID
|
||||
pk.VarInt(47), // Protocol version (1.8+)
|
||||
pk.String(host),
|
||||
pk.UnsignedShort(port),
|
||||
pk.VarInt(1), // Next state: Status
|
||||
)
|
||||
if err := conn.WritePacket(handshake); err != nil {
|
||||
return nil, fmt.Errorf("failed to send handshake: %w", err)
|
||||
}
|
||||
|
||||
// 发送状态请求
|
||||
request := pk.Marshal(0x00) // Status request packet ID
|
||||
if err := conn.WritePacket(request); err != nil {
|
||||
return nil, fmt.Errorf("failed to send status request: %w", err)
|
||||
}
|
||||
|
||||
// 读取响应
|
||||
var response pk.Packet
|
||||
if err := conn.ReadPacket(&response); err != nil {
|
||||
return nil, fmt.Errorf("failed to read response: %w", err)
|
||||
}
|
||||
|
||||
// 解析响应
|
||||
var statusJSON pk.String
|
||||
if err := response.Scan(&statusJSON); err != nil {
|
||||
return nil, fmt.Errorf("failed to parse response: %w", err)
|
||||
}
|
||||
|
||||
// 解析 JSON 响应
|
||||
var statusData map[string]interface{}
|
||||
if err := json.Unmarshal([]byte(statusJSON), &statusData); err != nil {
|
||||
return nil, fmt.Errorf("failed to parse JSON: %w", err)
|
||||
}
|
||||
|
||||
status := &ServerStatus{
|
||||
Host: host,
|
||||
Port: port,
|
||||
Latency: latency,
|
||||
}
|
||||
|
||||
// 解析 description
|
||||
if desc, ok := statusData["description"].(map[string]interface{}); ok {
|
||||
if text, ok := desc["text"].(string); ok {
|
||||
status.Description = text
|
||||
} else if text, ok := desc["extra"].([]interface{}); ok && len(text) > 0 {
|
||||
// 处理 extra 数组
|
||||
var descText strings.Builder
|
||||
for _, item := range text {
|
||||
if itemMap, ok := item.(map[string]interface{}); ok {
|
||||
if text, ok := itemMap["text"].(string); ok {
|
||||
descText.WriteString(text)
|
||||
}
|
||||
}
|
||||
}
|
||||
status.Description = descText.String()
|
||||
}
|
||||
} else if desc, ok := statusData["description"].(string); ok {
|
||||
status.Description = desc
|
||||
}
|
||||
|
||||
// 解析 version
|
||||
if version, ok := statusData["version"].(map[string]interface{}); ok {
|
||||
if name, ok := version["name"].(string); ok {
|
||||
status.Version.Name = name
|
||||
}
|
||||
if protocol, ok := version["protocol"].(float64); ok {
|
||||
status.Version.Protocol = int(protocol)
|
||||
}
|
||||
}
|
||||
|
||||
// 解析 players
|
||||
if players, ok := statusData["players"].(map[string]interface{}); ok {
|
||||
if online, ok := players["online"].(float64); ok {
|
||||
status.Players.Online = int(online)
|
||||
}
|
||||
if max, ok := players["max"].(float64); ok {
|
||||
status.Players.Max = int(max)
|
||||
}
|
||||
}
|
||||
|
||||
// 解析 favicon
|
||||
if favicon, ok := statusData["favicon"].(string); ok {
|
||||
// 移除 data:image/png;base64, 前缀
|
||||
if strings.HasPrefix(favicon, "data:image/png;base64,") {
|
||||
status.Favicon = strings.TrimPrefix(favicon, "data:image/png;base64,")
|
||||
} else {
|
||||
status.Favicon = favicon
|
||||
}
|
||||
}
|
||||
|
||||
return status, nil
|
||||
}
|
||||
347
internal/plugins/welcome/welcome.go
Normal file
347
internal/plugins/welcome/welcome.go
Normal file
@@ -0,0 +1,347 @@
|
||||
package welcome
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"cellbot/internal/engine"
|
||||
"cellbot/internal/protocol"
|
||||
"cellbot/pkg/utils"
|
||||
|
||||
"go.uber.org/zap"
|
||||
)
|
||||
|
||||
func init() {
|
||||
// 监听群成员增加通知事件
|
||||
engine.OnNotice("group_increase").
|
||||
Priority(50). // 设置较高优先级,确保及时响应
|
||||
Handle(handleWelcomeEvent)
|
||||
}
|
||||
|
||||
// handleWelcomeEvent 处理群成员加入欢迎事件
|
||||
func handleWelcomeEvent(ctx context.Context, event protocol.Event, botManager *protocol.BotManager, logger *zap.Logger) error {
|
||||
logger.Info("Welcome event received",
|
||||
zap.String("event_type", string(event.GetType())),
|
||||
zap.String("detail_type", event.GetDetailType()),
|
||||
zap.String("sub_type", event.GetSubType()),
|
||||
zap.String("self_id", event.GetSelfID()))
|
||||
|
||||
// 注意:中间件已经过滤了 detail_type,这里可以简化检查
|
||||
data := event.GetData()
|
||||
logger.Debug("Event data", zap.Any("data", data))
|
||||
|
||||
// 获取群ID和用户ID
|
||||
groupID, ok := data["group_id"]
|
||||
if !ok {
|
||||
logger.Warn("Missing group_id in event data")
|
||||
return nil
|
||||
}
|
||||
|
||||
userID, ok := data["user_id"]
|
||||
if !ok {
|
||||
logger.Warn("Missing user_id in event data")
|
||||
return nil
|
||||
}
|
||||
|
||||
logger.Info("Processing welcome event",
|
||||
zap.Any("group_id", groupID),
|
||||
zap.Any("user_id", userID))
|
||||
|
||||
// 获取操作者ID(邀请者或审批者)
|
||||
var operatorID interface{}
|
||||
if opID, exists := data["operator_id"]; exists {
|
||||
operatorID = opID
|
||||
}
|
||||
|
||||
// 获取子类型(approve: 管理员同意, invite: 邀请)
|
||||
subType := event.GetSubType()
|
||||
|
||||
// 获取 bot 实例
|
||||
selfID := event.GetSelfID()
|
||||
bot, ok := botManager.Get(selfID)
|
||||
if !ok {
|
||||
bots := botManager.GetAll()
|
||||
if len(bots) == 0 {
|
||||
logger.Error("No bot instance available")
|
||||
return nil
|
||||
}
|
||||
bot = bots[0]
|
||||
}
|
||||
|
||||
// 构建欢迎消息链(使用HTML模板渲染图片)
|
||||
logger.Info("Building welcome message",
|
||||
zap.Any("user_id", userID),
|
||||
zap.Any("operator_id", operatorID),
|
||||
zap.String("sub_type", subType))
|
||||
|
||||
welcomeChain, err := buildWelcomeMessage(ctx, userID, operatorID, subType, logger)
|
||||
if err != nil {
|
||||
logger.Error("Failed to build welcome message",
|
||||
zap.Any("user_id", userID),
|
||||
zap.Any("operator_id", operatorID),
|
||||
zap.String("sub_type", subType),
|
||||
zap.Error(err))
|
||||
return err
|
||||
}
|
||||
|
||||
logger.Info("Welcome message built successfully",
|
||||
zap.Int("chain_length", len(welcomeChain)))
|
||||
|
||||
// 发送群消息
|
||||
logger.Info("Sending welcome message",
|
||||
zap.Any("group_id", groupID),
|
||||
zap.Any("user_id", userID))
|
||||
|
||||
action := &protocol.BaseAction{
|
||||
Type: protocol.ActionTypeSendGroupMessage,
|
||||
Params: map[string]interface{}{
|
||||
"group_id": groupID,
|
||||
"message": welcomeChain,
|
||||
},
|
||||
}
|
||||
|
||||
result, err := bot.SendAction(ctx, action)
|
||||
if err != nil {
|
||||
logger.Error("Failed to send welcome message",
|
||||
zap.Any("group_id", groupID),
|
||||
zap.Any("user_id", userID),
|
||||
zap.Any("action_type", action.Type),
|
||||
zap.Error(err))
|
||||
return err
|
||||
}
|
||||
|
||||
logger.Info("Welcome message sent successfully",
|
||||
zap.Any("group_id", groupID),
|
||||
zap.Any("user_id", userID),
|
||||
zap.Any("result", result))
|
||||
|
||||
logger.Info("Welcome message sent",
|
||||
zap.Any("group_id", groupID),
|
||||
zap.Any("user_id", userID),
|
||||
zap.String("sub_type", subType))
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// welcomeTemplate HTML欢迎消息模板
|
||||
const welcomeTemplate = `
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<style>
|
||||
* {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
body {
|
||||
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
|
||||
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
|
||||
padding: 40px 20px;
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
align-items: center;
|
||||
min-height: 100vh;
|
||||
}
|
||||
.container {
|
||||
background: white;
|
||||
border-radius: 20px;
|
||||
padding: 40px;
|
||||
max-width: 600px;
|
||||
width: 100%;
|
||||
box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);
|
||||
}
|
||||
.header {
|
||||
text-align: center;
|
||||
margin-bottom: 30px;
|
||||
}
|
||||
.welcome-icon {
|
||||
font-size: 64px;
|
||||
margin-bottom: 10px;
|
||||
}
|
||||
.title {
|
||||
font-size: 32px;
|
||||
font-weight: bold;
|
||||
color: #333;
|
||||
margin-bottom: 10px;
|
||||
}
|
||||
.subtitle {
|
||||
font-size: 18px;
|
||||
color: #666;
|
||||
}
|
||||
.content {
|
||||
margin: 30px 0;
|
||||
}
|
||||
.user-info {
|
||||
background: #f8f9fa;
|
||||
border-radius: 10px;
|
||||
padding: 20px;
|
||||
margin: 20px 0;
|
||||
}
|
||||
.info-item {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
padding: 10px 0;
|
||||
border-bottom: 1px solid #e9ecef;
|
||||
}
|
||||
.info-item:last-child {
|
||||
border-bottom: none;
|
||||
}
|
||||
.info-label {
|
||||
font-weight: 600;
|
||||
color: #495057;
|
||||
}
|
||||
.info-value {
|
||||
color: #212529;
|
||||
}
|
||||
.join-type {
|
||||
text-align: center;
|
||||
padding: 15px;
|
||||
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
|
||||
color: white;
|
||||
border-radius: 10px;
|
||||
margin: 20px 0;
|
||||
font-weight: 600;
|
||||
}
|
||||
.tips {
|
||||
background: #e7f3ff;
|
||||
border-left: 4px solid #2196F3;
|
||||
padding: 15px;
|
||||
border-radius: 5px;
|
||||
margin: 20px 0;
|
||||
}
|
||||
.tips-title {
|
||||
font-weight: 600;
|
||||
color: #1976D2;
|
||||
margin-bottom: 10px;
|
||||
}
|
||||
.tips-list {
|
||||
list-style: none;
|
||||
padding-left: 0;
|
||||
}
|
||||
.tips-list li {
|
||||
padding: 5px 0;
|
||||
color: #424242;
|
||||
}
|
||||
.tips-list li:before {
|
||||
content: "• ";
|
||||
color: #2196F3;
|
||||
font-weight: bold;
|
||||
}
|
||||
.footer {
|
||||
text-align: center;
|
||||
margin-top: 30px;
|
||||
color: #999;
|
||||
font-size: 14px;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="container">
|
||||
<div class="header">
|
||||
<div class="welcome-icon">🎉</div>
|
||||
<div class="title">欢迎加入!</div>
|
||||
<div class="subtitle">Welcome to the Group</div>
|
||||
</div>
|
||||
|
||||
<div class="content">
|
||||
<div class="user-info">
|
||||
<div class="info-item">
|
||||
<span class="info-label">用户ID:</span>
|
||||
<span class="info-value">{{.UserID}}</span>
|
||||
</div>
|
||||
{{if .OperatorID}}
|
||||
<div class="info-item">
|
||||
<span class="info-label">{{.OperatorLabel}}:</span>
|
||||
<span class="info-value">{{.OperatorID}}</span>
|
||||
</div>
|
||||
{{end}}
|
||||
</div>
|
||||
|
||||
{{if .JoinType}}
|
||||
<div class="join-type">
|
||||
{{.JoinType}}
|
||||
</div>
|
||||
{{end}}
|
||||
|
||||
<div class="tips">
|
||||
<div class="tips-title">💡 温馨提示</div>
|
||||
<ul class="tips-list">
|
||||
<li>请遵守群规,文明交流</li>
|
||||
<li>如有问题可以@管理员</li>
|
||||
<li>发送 /help 查看帮助</li>
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="footer">
|
||||
希望你在群里玩得开心!
|
||||
</div>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
`
|
||||
|
||||
// buildWelcomeMessage 构建欢迎消息链(使用HTML模板渲染图片)
|
||||
func buildWelcomeMessage(ctx context.Context, userID, operatorID interface{}, subType string, logger *zap.Logger) (protocol.MessageChain, error) {
|
||||
logger.Debug("Starting to build welcome message",
|
||||
zap.Any("user_id", userID),
|
||||
zap.Any("operator_id", operatorID),
|
||||
zap.String("sub_type", subType))
|
||||
|
||||
// 准备模板数据
|
||||
data := map[string]interface{}{
|
||||
"UserID": fmt.Sprintf("%v", userID),
|
||||
}
|
||||
logger.Debug("Template data prepared", zap.Any("data", data))
|
||||
|
||||
// 根据加入方式设置不同的信息
|
||||
switch subType {
|
||||
case "approve":
|
||||
data["JoinType"] = "✅ 管理员审批通过"
|
||||
if operatorID != nil {
|
||||
data["OperatorID"] = fmt.Sprintf("%v", operatorID)
|
||||
data["OperatorLabel"] = "审批管理员"
|
||||
}
|
||||
case "invite":
|
||||
data["JoinType"] = "👥 被邀请加入"
|
||||
if operatorID != nil {
|
||||
data["OperatorID"] = fmt.Sprintf("%v", operatorID)
|
||||
data["OperatorLabel"] = "邀请人"
|
||||
}
|
||||
default:
|
||||
data["JoinType"] = "🎊 加入群聊"
|
||||
}
|
||||
|
||||
// 配置截图选项
|
||||
opts := &utils.ScreenshotOptions{
|
||||
Width: 1200, // 增加宽度,确保内容有足够空间
|
||||
Height: 800, // 增加高度,确保内容完整显示
|
||||
Timeout: 60 * time.Second, // 增加超时时间到60秒
|
||||
WaitTime: 3 * time.Second, // 增加等待时间,确保页面完全加载
|
||||
FullPage: false,
|
||||
Quality: 90,
|
||||
Logger: logger,
|
||||
}
|
||||
|
||||
// 渲染模板并截图
|
||||
logger.Info("Rendering template and taking screenshot",
|
||||
zap.Int("width", opts.Width),
|
||||
zap.Int("height", opts.Height),
|
||||
zap.Duration("timeout", opts.Timeout))
|
||||
|
||||
chain, err := utils.ScreenshotTemplateToMessageChain(ctx, welcomeTemplate, data, opts)
|
||||
if err != nil {
|
||||
logger.Error("Failed to render welcome template",
|
||||
zap.Any("data", data),
|
||||
zap.Error(err))
|
||||
return nil, fmt.Errorf("failed to render welcome template: %w", err)
|
||||
}
|
||||
|
||||
logger.Info("Template rendered and screenshot taken successfully",
|
||||
zap.Int("chain_length", len(chain)))
|
||||
|
||||
return chain, nil
|
||||
}
|
||||
@@ -1,19 +1,24 @@
|
||||
package protocol
|
||||
|
||||
import "time"
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"go.uber.org/zap"
|
||||
)
|
||||
|
||||
// EventType 事件类型
|
||||
type EventType string
|
||||
|
||||
const (
|
||||
// 事件类型常量
|
||||
EventTypeMessage EventType = "message"
|
||||
EventTypeNotice EventType = "notice"
|
||||
EventTypeRequest EventType = "request"
|
||||
EventTypeMeta EventType = "meta"
|
||||
EventTypeMessageSent EventType = "message_sent"
|
||||
EventTypeNoticeSent EventType = "notice_sent"
|
||||
EventTypeRequestSent EventType = "request_sent"
|
||||
EventTypeMessage EventType = "message"
|
||||
EventTypeNotice EventType = "notice"
|
||||
EventTypeRequest EventType = "request"
|
||||
EventTypeMeta EventType = "meta"
|
||||
EventTypeMessageSent EventType = "message_sent"
|
||||
EventTypeNoticeSent EventType = "notice_sent"
|
||||
EventTypeRequestSent EventType = "request_sent"
|
||||
)
|
||||
|
||||
// Event 通用事件接口
|
||||
@@ -31,6 +36,10 @@ type Event interface {
|
||||
GetSelfID() string
|
||||
// GetData 获取事件数据
|
||||
GetData() map[string]interface{}
|
||||
// Reply 在消息发生的群/私聊进行回复
|
||||
Reply(ctx context.Context, botManager *BotManager, logger *zap.Logger, message MessageChain) error
|
||||
// ReplyText 在消息发生的群/私聊进行文本回复(便捷方法)
|
||||
ReplyText(ctx context.Context, botManager *BotManager, logger *zap.Logger, text string) error
|
||||
}
|
||||
|
||||
// BaseEvent 基础事件结构
|
||||
@@ -73,6 +82,70 @@ func (e *BaseEvent) GetData() map[string]interface{} {
|
||||
return e.Data
|
||||
}
|
||||
|
||||
// Reply 在消息发生的群/私聊进行回复
|
||||
func (e *BaseEvent) Reply(ctx context.Context, botManager *BotManager, logger *zap.Logger, message MessageChain) error {
|
||||
data := e.GetData()
|
||||
userID, _ := data["user_id"]
|
||||
groupID, _ := data["group_id"]
|
||||
|
||||
// 获取 bot 实例
|
||||
selfID := e.GetSelfID()
|
||||
bot, ok := botManager.Get(selfID)
|
||||
if !ok {
|
||||
bots := botManager.GetAll()
|
||||
if len(bots) == 0 {
|
||||
logger.Error("No bot instance available")
|
||||
return nil
|
||||
}
|
||||
bot = bots[0]
|
||||
}
|
||||
|
||||
// 根据消息类型发送回复
|
||||
var action *BaseAction
|
||||
if e.GetDetailType() == "private" {
|
||||
action = &BaseAction{
|
||||
Type: ActionTypeSendPrivateMessage,
|
||||
Params: map[string]interface{}{
|
||||
"user_id": userID,
|
||||
"message": message,
|
||||
},
|
||||
}
|
||||
} else {
|
||||
// 群聊或其他有 group_id 的事件
|
||||
action = &BaseAction{
|
||||
Type: ActionTypeSendGroupMessage,
|
||||
Params: map[string]interface{}{
|
||||
"group_id": groupID,
|
||||
"message": message,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
_, err := bot.SendAction(ctx, action)
|
||||
if err != nil {
|
||||
logger.Error("Failed to send reply",
|
||||
zap.Any("user_id", userID),
|
||||
zap.Any("group_id", groupID),
|
||||
zap.String("detail_type", e.GetDetailType()),
|
||||
zap.Error(err))
|
||||
return err
|
||||
}
|
||||
|
||||
logger.Debug("Reply sent",
|
||||
zap.Any("user_id", userID),
|
||||
zap.Any("group_id", groupID),
|
||||
zap.String("detail_type", e.GetDetailType()))
|
||||
return nil
|
||||
}
|
||||
|
||||
// ReplyText 在消息发生的群/私聊进行文本回复(便捷方法)
|
||||
func (e *BaseEvent) ReplyText(ctx context.Context, botManager *BotManager, logger *zap.Logger, text string) error {
|
||||
message := NewMessageChain(
|
||||
NewTextSegment(text),
|
||||
)
|
||||
return e.Reply(ctx, botManager, logger, message)
|
||||
}
|
||||
|
||||
// MessageEvent 消息事件
|
||||
type MessageEvent struct {
|
||||
BaseEvent
|
||||
|
||||
133
internal/protocol/message.go
Normal file
133
internal/protocol/message.go
Normal file
@@ -0,0 +1,133 @@
|
||||
package protocol
|
||||
|
||||
import "fmt"
|
||||
|
||||
// MessageSegment 消息段(基于 OneBot12 设计)
|
||||
// 通用消息段结构,适配器负责转换为具体协议格式
|
||||
type MessageSegment struct {
|
||||
Type string `json:"type"` // 消息段类型
|
||||
Data map[string]interface{} `json:"data"` // 消息段数据
|
||||
}
|
||||
|
||||
// MessageChain 消息链(基于 OneBot12 设计)
|
||||
// 消息由多个消息段组成
|
||||
type MessageChain []MessageSegment
|
||||
|
||||
// 消息段类型常量(基于 OneBot12)
|
||||
const (
|
||||
SegmentTypeText = "text" // 文本
|
||||
SegmentTypeMention = "mention" // @提及(OneBot12)
|
||||
SegmentTypeImage = "image" // 图片
|
||||
SegmentTypeVoice = "voice" // 语音
|
||||
SegmentTypeVideo = "video" // 视频
|
||||
SegmentTypeFile = "file" // 文件
|
||||
SegmentTypeLocation = "location" // 位置
|
||||
SegmentTypeReply = "reply" // 回复
|
||||
SegmentTypeForward = "forward" // 转发
|
||||
SegmentTypeFace = "face" // 表情(QQ)
|
||||
SegmentTypeAt = "at" // @提及(OneBot11 兼容)
|
||||
SegmentTypeRecord = "record" // 语音(OneBot11 兼容)
|
||||
)
|
||||
|
||||
// NewTextSegment 创建文本消息段
|
||||
func NewTextSegment(text string) MessageSegment {
|
||||
return MessageSegment{
|
||||
Type: SegmentTypeText,
|
||||
Data: map[string]interface{}{
|
||||
"text": text,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// NewMentionSegment 创建@提及消息段(OneBot12 标准)
|
||||
func NewMentionSegment(userID interface{}) MessageSegment {
|
||||
return MessageSegment{
|
||||
Type: SegmentTypeMention,
|
||||
Data: map[string]interface{}{
|
||||
"user_id": userID,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// NewImageSegment 创建图片消息段
|
||||
func NewImageSegment(fileID string) MessageSegment {
|
||||
return MessageSegment{
|
||||
Type: SegmentTypeImage,
|
||||
Data: map[string]interface{}{
|
||||
"file_id": fileID,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// NewImageSegmentFromBase64 从base64字符串创建图片消息段
|
||||
func NewImageSegmentFromBase64(base64Data string) MessageSegment {
|
||||
return MessageSegment{
|
||||
Type: SegmentTypeImage,
|
||||
Data: map[string]interface{}{
|
||||
"file": fmt.Sprintf("base64://%s", base64Data),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// NewReplySegment 创建回复消息段
|
||||
func NewReplySegment(messageID interface{}) MessageSegment {
|
||||
return MessageSegment{
|
||||
Type: SegmentTypeReply,
|
||||
Data: map[string]interface{}{
|
||||
"message_id": messageID,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// NewMessageChain 创建消息链
|
||||
func NewMessageChain(segments ...MessageSegment) MessageChain {
|
||||
return MessageChain(segments)
|
||||
}
|
||||
|
||||
// Append 追加消息段到消息链
|
||||
func (mc MessageChain) Append(segments ...MessageSegment) MessageChain {
|
||||
return append(mc, segments...)
|
||||
}
|
||||
|
||||
// AppendText 追加文本到消息链
|
||||
func (mc MessageChain) AppendText(text string) MessageChain {
|
||||
return mc.Append(NewTextSegment(text))
|
||||
}
|
||||
|
||||
// AppendMention 追加@提及到消息链
|
||||
func (mc MessageChain) AppendMention(userID interface{}) MessageChain {
|
||||
return mc.Append(NewMentionSegment(userID))
|
||||
}
|
||||
|
||||
// AppendImage 追加图片到消息链
|
||||
func (mc MessageChain) AppendImage(fileID string) MessageChain {
|
||||
return mc.Append(NewImageSegment(fileID))
|
||||
}
|
||||
|
||||
// AppendImageFromBase64 从base64追加图片到消息链
|
||||
func (mc MessageChain) AppendImageFromBase64(base64Data string) MessageChain {
|
||||
return mc.Append(NewImageSegmentFromBase64(base64Data))
|
||||
}
|
||||
|
||||
// ToString 将消息链转换为字符串(用于调试)
|
||||
func (mc MessageChain) ToString() string {
|
||||
result := ""
|
||||
for _, seg := range mc {
|
||||
switch seg.Type {
|
||||
case SegmentTypeText:
|
||||
if text, ok := seg.Data["text"].(string); ok {
|
||||
result += text
|
||||
}
|
||||
case SegmentTypeMention, SegmentTypeAt:
|
||||
if userID, ok := seg.Data["user_id"]; ok {
|
||||
result += fmt.Sprintf("@%v", userID)
|
||||
} else if qq, ok := seg.Data["qq"]; ok {
|
||||
// OneBot11 兼容
|
||||
result += fmt.Sprintf("@%v", qq)
|
||||
}
|
||||
default:
|
||||
result += fmt.Sprintf("[%s]", seg.Type)
|
||||
}
|
||||
}
|
||||
return result
|
||||
}
|
||||
351
pkg/utils/screenshot.go
Normal file
351
pkg/utils/screenshot.go
Normal file
@@ -0,0 +1,351 @@
|
||||
package utils
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"cellbot/internal/protocol"
|
||||
"context"
|
||||
"encoding/base64"
|
||||
"fmt"
|
||||
"html/template"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"time"
|
||||
|
||||
"github.com/chromedp/chromedp"
|
||||
"go.uber.org/zap"
|
||||
)
|
||||
|
||||
// ScreenshotOptions 截图选项
|
||||
type ScreenshotOptions struct {
|
||||
Width int // 视口宽度(像素)
|
||||
Height int // 视口高度(像素)
|
||||
Timeout time.Duration // 超时时间
|
||||
WaitTime time.Duration // 等待时间(页面加载后等待)
|
||||
FullPage bool // 是否截取整个页面
|
||||
Quality int // 图片质量(0-100,仅PNG格式)
|
||||
Format string // 图片格式:png, jpeg
|
||||
Logger *zap.Logger // 日志记录器
|
||||
}
|
||||
|
||||
// DefaultScreenshotOptions 默认截图选项
|
||||
func DefaultScreenshotOptions() *ScreenshotOptions {
|
||||
return &ScreenshotOptions{
|
||||
Width: 1920,
|
||||
Height: 1080,
|
||||
Timeout: 30 * time.Second,
|
||||
WaitTime: 1 * time.Second,
|
||||
FullPage: false,
|
||||
Quality: 90,
|
||||
Format: "png",
|
||||
Logger: zap.NewNop(),
|
||||
}
|
||||
}
|
||||
|
||||
// ScreenshotURL 对指定URL进行截图并返回base64编码
|
||||
func ScreenshotURL(ctx context.Context, url string, opts *ScreenshotOptions) (string, error) {
|
||||
if opts == nil {
|
||||
opts = DefaultScreenshotOptions()
|
||||
}
|
||||
|
||||
// 创建上下文,添加优化选项
|
||||
allocCtx, cancel := chromedp.NewExecAllocator(ctx,
|
||||
chromedp.NoSandbox,
|
||||
chromedp.NoFirstRun,
|
||||
chromedp.NoDefaultBrowserCheck,
|
||||
chromedp.Headless,
|
||||
chromedp.DisableGPU,
|
||||
)
|
||||
defer cancel()
|
||||
|
||||
ctx, cancel = chromedp.NewContext(allocCtx, chromedp.WithLogf(func(format string, v ...interface{}) {
|
||||
if opts.Logger != nil {
|
||||
opts.Logger.Debug(fmt.Sprintf(format, v...))
|
||||
}
|
||||
}))
|
||||
defer cancel()
|
||||
|
||||
// 设置超时
|
||||
ctx, cancel = context.WithTimeout(ctx, opts.Timeout)
|
||||
defer cancel()
|
||||
|
||||
var buf []byte
|
||||
|
||||
// 执行截图任务
|
||||
var err error
|
||||
if opts.FullPage {
|
||||
err = chromedp.Run(ctx,
|
||||
chromedp.EmulateViewport(int64(opts.Width), int64(opts.Height)), // 设置视口大小
|
||||
chromedp.Navigate(url),
|
||||
chromedp.WaitReady("body", chromedp.ByQuery), // 使用 WaitReady 等待页面完全加载
|
||||
chromedp.Sleep(opts.WaitTime),
|
||||
chromedp.FullScreenshot(&buf, opts.Quality),
|
||||
)
|
||||
} else {
|
||||
err = chromedp.Run(ctx,
|
||||
chromedp.Navigate(url),
|
||||
chromedp.WaitReady("body", chromedp.ByQuery), // 使用 WaitReady 等待页面完全加载
|
||||
chromedp.Sleep(opts.WaitTime),
|
||||
chromedp.CaptureScreenshot(&buf),
|
||||
)
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("failed to capture screenshot: %w", err)
|
||||
}
|
||||
|
||||
// 转换为base64
|
||||
base64Str := base64.StdEncoding.EncodeToString(buf)
|
||||
return base64Str, nil
|
||||
}
|
||||
|
||||
// ScreenshotHTML 对HTML内容进行截图并返回base64编码
|
||||
func ScreenshotHTML(ctx context.Context, htmlContent string, opts *ScreenshotOptions) (string, error) {
|
||||
if opts == nil {
|
||||
opts = DefaultScreenshotOptions()
|
||||
}
|
||||
|
||||
if opts.Logger != nil {
|
||||
opts.Logger.Info("Starting HTML screenshot",
|
||||
zap.Int("html_length", len(htmlContent)),
|
||||
zap.Int("width", opts.Width),
|
||||
zap.Int("height", opts.Height),
|
||||
zap.Duration("timeout", opts.Timeout))
|
||||
}
|
||||
|
||||
// 创建上下文
|
||||
allocCtx, cancel := chromedp.NewExecAllocator(ctx,
|
||||
chromedp.NoSandbox,
|
||||
chromedp.NoFirstRun,
|
||||
chromedp.NoDefaultBrowserCheck,
|
||||
chromedp.Headless,
|
||||
chromedp.DisableGPU,
|
||||
)
|
||||
defer cancel()
|
||||
|
||||
if opts.Logger != nil {
|
||||
opts.Logger.Debug("Chrome allocator created")
|
||||
}
|
||||
|
||||
ctx, cancel = chromedp.NewContext(allocCtx, chromedp.WithLogf(func(format string, v ...interface{}) {
|
||||
if opts.Logger != nil {
|
||||
opts.Logger.Debug(fmt.Sprintf(format, v...))
|
||||
}
|
||||
}))
|
||||
defer cancel()
|
||||
|
||||
// 设置超时
|
||||
ctx, cancel = context.WithTimeout(ctx, opts.Timeout)
|
||||
defer cancel()
|
||||
|
||||
var buf []byte
|
||||
|
||||
// 使用 base64 编码的 data URL,避免 URL 编码导致的 + 号问题
|
||||
htmlBytes := []byte(htmlContent)
|
||||
htmlBase64 := base64.StdEncoding.EncodeToString(htmlBytes)
|
||||
dataURL := fmt.Sprintf("data:text/html;charset=utf-8;base64,%s", htmlBase64)
|
||||
|
||||
if opts.Logger != nil {
|
||||
opts.Logger.Debug("Navigating to base64 data URL",
|
||||
zap.Int("html_length", len(htmlContent)),
|
||||
zap.Int("base64_length", len(htmlBase64)))
|
||||
}
|
||||
|
||||
// 执行截图任务
|
||||
var err error
|
||||
if opts.FullPage {
|
||||
if opts.Logger != nil {
|
||||
opts.Logger.Debug("Taking full page screenshot")
|
||||
}
|
||||
err = chromedp.Run(ctx,
|
||||
chromedp.EmulateViewport(int64(opts.Width), int64(opts.Height)), // 设置视口大小
|
||||
chromedp.Navigate(dataURL),
|
||||
chromedp.WaitReady("body", chromedp.ByQuery),
|
||||
chromedp.Sleep(opts.WaitTime),
|
||||
chromedp.FullScreenshot(&buf, opts.Quality),
|
||||
)
|
||||
} else {
|
||||
if opts.Logger != nil {
|
||||
opts.Logger.Debug("Taking viewport screenshot")
|
||||
}
|
||||
err = chromedp.Run(ctx,
|
||||
chromedp.EmulateViewport(int64(opts.Width), int64(opts.Height)), // 设置视口大小
|
||||
chromedp.Navigate(dataURL),
|
||||
chromedp.WaitReady("body", chromedp.ByQuery),
|
||||
chromedp.Sleep(opts.WaitTime),
|
||||
chromedp.CaptureScreenshot(&buf),
|
||||
)
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
if opts.Logger != nil {
|
||||
opts.Logger.Error("Failed to capture screenshot", zap.Error(err))
|
||||
}
|
||||
return "", fmt.Errorf("failed to capture screenshot: %w", err)
|
||||
}
|
||||
|
||||
if opts.Logger != nil {
|
||||
opts.Logger.Info("Screenshot captured successfully",
|
||||
zap.Int("image_size", len(buf)))
|
||||
}
|
||||
|
||||
// 转换为base64
|
||||
base64Str := base64.StdEncoding.EncodeToString(buf)
|
||||
if opts.Logger != nil {
|
||||
opts.Logger.Info("Screenshot converted to base64",
|
||||
zap.Int("base64_length", len(base64Str)))
|
||||
}
|
||||
return base64Str, nil
|
||||
}
|
||||
|
||||
// ScreenshotElement 对页面中的特定元素进行截图
|
||||
func ScreenshotElement(ctx context.Context, url string, selector string, opts *ScreenshotOptions) (string, error) {
|
||||
if opts == nil {
|
||||
opts = DefaultScreenshotOptions()
|
||||
}
|
||||
|
||||
// 创建上下文
|
||||
allocCtx, cancel := chromedp.NewExecAllocator(ctx,
|
||||
chromedp.NoSandbox,
|
||||
chromedp.NoFirstRun,
|
||||
chromedp.NoDefaultBrowserCheck,
|
||||
chromedp.Headless,
|
||||
chromedp.DisableGPU,
|
||||
)
|
||||
defer cancel()
|
||||
|
||||
ctx, cancel = chromedp.NewContext(allocCtx, chromedp.WithLogf(func(format string, v ...interface{}) {
|
||||
if opts.Logger != nil {
|
||||
opts.Logger.Debug(fmt.Sprintf(format, v...))
|
||||
}
|
||||
}))
|
||||
defer cancel()
|
||||
|
||||
// 设置超时
|
||||
ctx, cancel = context.WithTimeout(ctx, opts.Timeout)
|
||||
defer cancel()
|
||||
|
||||
var buf []byte
|
||||
|
||||
// 执行截图任务
|
||||
err := chromedp.Run(ctx,
|
||||
chromedp.Navigate(url),
|
||||
chromedp.WaitVisible(selector, chromedp.ByQuery),
|
||||
chromedp.Sleep(opts.WaitTime),
|
||||
chromedp.Screenshot(selector, &buf, chromedp.NodeVisible),
|
||||
)
|
||||
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("failed to capture element screenshot: %w", err)
|
||||
}
|
||||
|
||||
// 转换为base64
|
||||
base64Str := base64.StdEncoding.EncodeToString(buf)
|
||||
return base64Str, nil
|
||||
}
|
||||
|
||||
// ScreenshotHTMLToMessageChain 对HTML内容进行截图并返回包含图片的消息链
|
||||
func ScreenshotHTMLToMessageChain(ctx context.Context, htmlContent string, opts *ScreenshotOptions) (protocol.MessageChain, error) {
|
||||
base64Data, err := ScreenshotHTML(ctx, htmlContent, opts)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
chain := protocol.NewMessageChain()
|
||||
chain = chain.AppendImageFromBase64(base64Data)
|
||||
return chain, nil
|
||||
}
|
||||
|
||||
// ScreenshotURLToMessageChain 对URL进行截图并返回包含图片的消息链
|
||||
func ScreenshotURLToMessageChain(ctx context.Context, url string, opts *ScreenshotOptions) (protocol.MessageChain, error) {
|
||||
base64Data, err := ScreenshotURL(ctx, url, opts)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
chain := protocol.NewMessageChain()
|
||||
chain = chain.AppendImageFromBase64(base64Data)
|
||||
return chain, nil
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// HTML 模板功能
|
||||
// ============================================================================
|
||||
|
||||
// RenderHTMLTemplate 渲染HTML模板并返回HTML字符串
|
||||
func RenderHTMLTemplate(tmplContent string, data interface{}) (string, error) {
|
||||
tmpl, err := template.New("html").Parse(tmplContent)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("failed to parse template: %w", err)
|
||||
}
|
||||
|
||||
var buf bytes.Buffer
|
||||
if err := tmpl.Execute(&buf, data); err != nil {
|
||||
return "", fmt.Errorf("failed to execute template: %w", err)
|
||||
}
|
||||
|
||||
return buf.String(), nil
|
||||
}
|
||||
|
||||
// RenderHTMLTemplateFromFile 从文件加载并渲染HTML模板
|
||||
func RenderHTMLTemplateFromFile(tmplPath string, data interface{}) (string, error) {
|
||||
content, err := os.ReadFile(tmplPath)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("failed to read template file: %w", err)
|
||||
}
|
||||
|
||||
tmpl, err := template.New(filepath.Base(tmplPath)).Parse(string(content))
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("failed to parse template: %w", err)
|
||||
}
|
||||
|
||||
var buf bytes.Buffer
|
||||
if err := tmpl.Execute(&buf, data); err != nil {
|
||||
return "", fmt.Errorf("failed to execute template: %w", err)
|
||||
}
|
||||
|
||||
return buf.String(), nil
|
||||
}
|
||||
|
||||
// ScreenshotTemplate 渲染HTML模板并截图,返回base64编码
|
||||
func ScreenshotTemplate(ctx context.Context, tmplContent string, data interface{}, opts *ScreenshotOptions) (string, error) {
|
||||
html, err := RenderHTMLTemplate(tmplContent, data)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
return ScreenshotHTML(ctx, html, opts)
|
||||
}
|
||||
|
||||
// ScreenshotTemplateFromFile 从文件加载模板,渲染并截图,返回base64编码
|
||||
func ScreenshotTemplateFromFile(ctx context.Context, tmplPath string, data interface{}, opts *ScreenshotOptions) (string, error) {
|
||||
html, err := RenderHTMLTemplateFromFile(tmplPath, data)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
return ScreenshotHTML(ctx, html, opts)
|
||||
}
|
||||
|
||||
// ScreenshotTemplateToMessageChain 渲染HTML模板并截图,返回包含图片的消息链
|
||||
func ScreenshotTemplateToMessageChain(ctx context.Context, tmplContent string, data interface{}, opts *ScreenshotOptions) (protocol.MessageChain, error) {
|
||||
base64Data, err := ScreenshotTemplate(ctx, tmplContent, data, opts)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
chain := protocol.NewMessageChain()
|
||||
chain = chain.AppendImageFromBase64(base64Data)
|
||||
return chain, nil
|
||||
}
|
||||
|
||||
// ScreenshotTemplateFromFileToMessageChain 从文件加载模板,渲染并截图,返回包含图片的消息链
|
||||
func ScreenshotTemplateFromFileToMessageChain(ctx context.Context, tmplPath string, data interface{}, opts *ScreenshotOptions) (protocol.MessageChain, error) {
|
||||
base64Data, err := ScreenshotTemplateFromFile(ctx, tmplPath, data, opts)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
chain := protocol.NewMessageChain()
|
||||
chain = chain.AppendImageFromBase64(base64Data)
|
||||
return chain, nil
|
||||
}
|
||||
Reference in New Issue
Block a user