-
Notifications
You must be signed in to change notification settings - Fork 7
/
bot.go
79 lines (70 loc) · 2.21 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
package viberbotapi
import (
"bytes"
"github.com/pkg/errors"
"github.com/pquerna/ffjson/ffjson"
"github.com/strongo/bots-api-viber/viberinterface"
"io/ioutil"
"net/http"
)
const (
// ViberAPIBaseURL is a base API url
ViberAPIBaseURL = "https://chatapi.viber.com/pa/"
)
// ViberBotAPI allows you to interact with the Viber Bot API.
type ViberBotAPI struct {
httpClient *http.Client
token string
}
// NewViberBotAPIWithHTTPClient creates new API provider with HTTP client
func NewViberBotAPIWithHTTPClient(token string, httpClient *http.Client) *ViberBotAPI {
return &ViberBotAPI{token: token, httpClient: httpClient}
}
// SetWebhook sets webhook to the specified URL
func (botApi ViberBotAPI) SetWebhook(url string, eventTypes []string) (response viberinterface.SetWebhookResponse, err error) {
var responseBody []byte
if _, responseBody, err = botApi.send(
&viberinterface.SetWebhookMessage{
ViberAuth: viberinterface.ViberAuth{Token: botApi.token},
Url: url,
EventTypes: eventTypes,
},
); err != nil {
return
}
if err = ffjson.UnmarshalFast(responseBody, &response); err != nil {
err = errors.Wrap(err, "Failed to unmarshal response body to JSON")
return
}
return
}
// SendMessage sends messages to Viber
func (botApi ViberBotAPI) SendMessage(m viberinterface.MessageToReceiver) (requestBody []byte, response viberinterface.SendMessageResponse, err error) {
m.SetType(m.GetType())
m.SetToken(botApi.token)
var responseBody []byte
if requestBody, responseBody, err = botApi.send(m); err != nil {
return
}
if err = ffjson.UnmarshalFast(responseBody, &response); err != nil {
err = errors.Wrap(err, "Failed to unmarshal response body to JSON")
}
return
}
func (botApi ViberBotAPI) send(m viberinterface.MessageToViberEndpoint) (requestBody []byte, responseBody []byte, err error) {
if requestBody, err = ffjson.MarshalFast(m); err != nil {
ffjson.Pool(requestBody)
return
}
var resp *http.Response
endpointURL := ViberAPIBaseURL + m.Endpoint()
resp, err = botApi.httpClient.Post(endpointURL, "applicaiton/json", bytes.NewReader(requestBody))
ffjson.Pool(requestBody)
if err != nil {
return
}
if responseBody, err = ioutil.ReadAll(resp.Body); err != nil {
return
}
return
}