/
contact.go
79 lines (68 loc) · 1.77 KB
/
contact.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
package bot
import (
"encoding/json"
"github.com/mosqu1t0/Amigo-bot/utils/logcat"
)
func (bot *Bot) receive() {
_, bytes, err := bot.ws.ReadMessage()
if err != nil {
logcat.Error("Read bytes from ws error: ", err)
}
if DefaultBotConfig.Debug {
logcat.Debug(string(bytes))
}
var reckind RecvKind
json.Unmarshal(bytes, &reckind)
select {
case str := <-bot.getSign:
if DefaultBotConfig.Debug {
logcat.Debug("QuickTalk: ", str)
}
bot.sendChan <- bytes
default:
switch reckind.PostType {
case MsgPostType:
msg := new(RecvMessage)
json.Unmarshal(bytes, msg)
bot.handleMessage(msg)
case ReqPostType:
req := new(RecvRequest)
json.Unmarshal(bytes, req)
bot.handleRequest(req)
case NtsPostType:
nts := new(RecvNotice)
json.Unmarshal(bytes, nts)
bot.handleNotise(nts)
case MtaPostType:
mta := new(RecvMeta)
json.Unmarshal(bytes, mta)
bot.handleMeta(mta)
}
}
}
// 发送请求, 不处理响应信息, 如果发送失败会返回error
// 第一个参数是api的url,第二个参数是请求的 params struct
func (bot *Bot) Send(action string, v interface{}) error {
bytes, _ := json.Marshal(SendRespondJson{Action: action, Params: v, Echo: echo})
if DefaultBotConfig.Debug {
logcat.Debug(string(bytes))
}
err := bot.ws.WriteJSON(
SendRespondJson{Action: action, Params: v, Echo: echo},
)
if err != nil {
return err
}
return nil
}
// 快速反应,发送请求,接收json 的 []byte, 如果有错误会返回error
// 第一个参数是api的url,第二个参数是请求的 params struct
func (bot *Bot) QuickTalk(action string, v interface{}) ([]byte, error) {
errSend := bot.Send(action, v)
if errSend != nil {
return nil, errSend
}
bot.getSign <- action
bytes := (<-bot.sendChan).([]byte)
return bytes, nil
}