-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbot.go
93 lines (87 loc) · 2.08 KB
/
bot.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
package go_libonebot
import (
"github.com/FishZe/go-libonebot/connect"
"github.com/FishZe/go-libonebot/protocol"
"github.com/FishZe/go-libonebot/util"
"sync"
"time"
)
// Bot 一个oneBot实例
type Bot struct {
// connections 连接列表
connections sync.Map
// info 基本信息
info struct {
// self 自身字段 self
self protocol.Self
// version 版本
version string
// impl 实现名称
impl string
}
// requestChan 请求通道
requestChan chan protocol.RawRequestType
// handleMux 请求处理接口
handleMux *ActionMux
// heartBeatInterval 心跳间隔
heartBeatInterval int
}
// NewOneBot 获取一个OneBot实例
//
// 需要传入config配置和userId
func NewOneBot(config protocol.OneBotConfig, userId string) (b *Bot) {
b = new(Bot)
b.info.version = config.Version
b.info.impl = config.Implementation
b.info.self = protocol.Self{
PlatForm: config.PlatForm,
UserId: userId,
}
if config.HeartBeat.Enable {
if config.HeartBeat.Interval <= 0 {
b.heartBeatInterval = 5000
} else {
b.heartBeatInterval = config.HeartBeat.Interval
}
}
b.requestChan = make(chan protocol.RawRequestType, 65535)
b.startRequestChan()
// 开启心跳
go b.startHeartBeat()
return
}
// AddConnection 添加一个连接
func (b *Bot) AddConnection(c connect.Connection) error {
// 双向绑定 向连接添加机器人
err := c.AddBot(b.info.impl, b.info.version, c.GetVersion(), b.info.self)
if err != nil {
return err
}
// 绑定请求通道
err = c.AddBotRequestChan(b.info.self, b.requestChan)
if err != nil {
return err
}
// 加入所有连接
b.connections.Store(c.GetUUID(), &c)
return nil
}
// Handle 绑定处理器
func (b *Bot) Handle(mux *ActionMux) {
b.handleMux = mux
}
// startHeartBeat 开启心跳
// @receiver b
func (b *Bot) startHeartBeat() {
if b.heartBeatInterval <= 0 {
return
}
for {
e := protocol.NewMetaEventHeartbeat()
e.Interval = b.heartBeatInterval
if err := b.SendEvent(e); err != nil {
util.Logger.Error("send heartbeat error: " + err.Error())
}
time.Sleep(time.Duration(b.heartBeatInterval) * time.Millisecond)
}
}