-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcleverbot.go
99 lines (81 loc) · 1.72 KB
/
cleverbot.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
94
95
96
97
98
99
// Package cleverbot implements wrapper for the cleverbot.io API.
package cleverbot
import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
)
// API Endpoints.
const (
baseURL = "https://cleverbot.io/1.0/"
createURL = baseURL + "create"
askURL = baseURL + "ask"
)
// New bot instance.
// "nick" is optional if you did not specify it, a random one is generated for you.
// A successful call returns err == nil.
func New(user, key string, nick ...string) (s *Session, err error) {
var sessionName string
if len(nick) > 0 {
sessionName = nick[0]
}
s = &Session{
User: user,
Key: key,
Nick: sessionName,
}
params, err := json.Marshal(s)
if err != nil {
return
}
response, err := http.Post(createURL, "application/json", bytes.NewBuffer(params))
if err != nil {
return
}
body, err := ioutil.ReadAll(response.Body)
if err != nil {
return
}
m := map[string]string{}
err = json.Unmarshal([]byte(body), &m)
if err != nil {
return
}
if m["status"] == "success" {
s.Nick = m["nick"]
} else {
err = fmt.Errorf(m["status"])
return
}
return
}
// Ask Cleverbot a question, returns Cleverbots response.
// A successful call returns err == nil.
func (s *Session) Ask(text string) (output string, err error) {
s.Text = text
params, err := json.Marshal(s)
if err != nil {
return
}
response, err := http.Post(askURL, "application/json", bytes.NewBuffer(params))
if err != nil {
return
}
body, err := ioutil.ReadAll(response.Body)
if err != nil {
return
}
m := map[string]string{}
err = json.Unmarshal([]byte(body), &m)
if err != nil {
return
}
if m["status"] != "success" {
err = fmt.Errorf(m["status"])
return
}
// return the bots asnwer.
return m["response"], nil
}