forked from huoxue1/leafbot
/
bot.go
78 lines (69 loc) · 1.23 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
package cqhttp_reverse_ws_driver
import (
"errors"
"sync"
"time"
"github.com/gorilla/websocket"
)
// Bot
// @Description: bot实例对象
//
type Bot struct {
selfId int64
conn *websocket.Conn
responses sync.Map
lock sync.Mutex
disConnectHandle func(selfId int64)
}
// GetSelfId
/**
* @Description: 获取bot的账号
* @receiver b
* @return int64
* example
*/
func (b *Bot) GetSelfId() int64 {
return b.selfId
}
// Do
/**
* @Description: 执行一个api的调用
* @receiver b
* @param i
* example
*/
func (b *Bot) Do(i interface{}) {
err := b.conn.WriteJSON(i)
if err != nil {
b.wsClose()
return
}
}
// GetResponse
/**
* @Description: 获取一个api调用的响应
* @receiver b
* @param echo api调用的唯一标识
* @return []byte
* @return error
* example
*/
func (b *Bot) GetResponse(echo string) ([]byte, error) {
defer func() {
b.responses.Delete(echo)
}()
for i := 0; i < 120; i++ {
value, ok := b.responses.LoadAndDelete(echo)
if ok {
return value.([]byte), nil
}
time.Sleep(500)
}
return nil, errors.New("get response time out")
}
func (b *Bot) wsClose() {
_ = b.conn.Close()
b.lock.Lock()
b.disConnectHandle(b.selfId)
defer b.lock.Unlock()
}