/
bot.go
88 lines (79 loc) · 1.55 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
package cqhttp_http_driver
import (
"errors"
"fmt"
"sync"
"time"
"github.com/guonaihong/gout"
log "github.com/sirupsen/logrus"
)
// Bot
// @Description:
//
type Bot struct {
client *gout.Client
selfID int64
responses sync.Map
token string
disConnectHandle func(selfId int64)
postHost string
postPort int
}
// GetSelfId
/**
* @Description:
* @receiver b
* @return int64
*/
func (b *Bot) GetSelfId() int64 {
return b.selfID
}
// Do
/**
* @Description:
* @receiver b
* @param i
*/
func (b *Bot) Do(i interface{}) {
type userAPi struct {
Action string `json:"action"`
Params interface{} `json:"params"`
Echo string `json:"echo"`
}
data := i.(userAPi)
var resp []byte
err := b.client.POST(fmt.Sprintf("http://%v:%v/%v", b.postHost, b.postPort, data.Action)).
SetHeader(gout.H{"Authorization": "Bearer " + b.token}).
SetJSON(data.Params).
BindBody(&resp).Do()
if err != nil {
log.Errorln("调用api出现错误", err.Error())
return
}
b.responses.Store(data.Echo, resp)
}
// 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() {
// todo
}