-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathturing.go
89 lines (75 loc) · 1.83 KB
/
turing.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
package main
import (
"bytes"
"encoding/json"
"io/ioutil"
"log"
"net/http"
"tonycat/config"
)
type InputMessage struct {
ReqType int `json:"reqType"`
*Perception `json:"perception"`
*UserInfo `json:"userInfo"`
}
type Perception struct {
*InputText `json:"inputText"`
}
type InputText struct {
Text string `json:"text"`
}
type UserInfo struct {
ApiKey string `json:"apiKey"`
UserId string `json:"userId"`
}
type OutPutMessage struct {
Intent *OutIntent `json:"intent"`
Results []Results `json:"results"`
}
type OutIntent struct {
Code int `json:"code"`
}
type Results struct {
ResultType string `json:"resultType"`
Values map[string]string `json:"values"`
GroupType int `json:"groupType"`
}
type TuringBot struct{}
func (tb *TuringBot) Chat(message string) string {
input := InputMessage{
ReqType: 0,
Perception: &Perception{
InputText: &InputText{Text: message},
},
UserInfo: &UserInfo{ApiKey: config.TURING_APIKEY, UserId: config.TURING_USERID},
}
b, _ := json.Marshal(input)
// log.Println("send:", string(b))
client := &http.Client{}
request, _ := http.NewRequest("POST", config.TURING_OPEN_API, bytes.NewBuffer(b))
request.Header.Set("Content-type", "application/json")
response, _ := client.Do(request)
if response.StatusCode == 200 {
body, _ := ioutil.ReadAll(response.Body)
log.Println("bot return:", string(body))
outMessage := OutPutMessage{}
outMessage.Results = make([]Results, 0)
err := json.Unmarshal(body, &outMessage)
if err != nil {
log.Printf("err: %v", err)
}
// fmt.Println(outMessage.Results[0].Values["text"])
if len(outMessage.Results) > 0 {
txt := outMessage.Results[0].Values["text"]
if txt != "" {
return txt
} else {
return outMessage.Results[0].Values["url"]
}
} else {
return ""
}
} else {
return ""
}
}