-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathworkwxbot.go
63 lines (52 loc) · 1.13 KB
/
workwxbot.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
package workwxbot
import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
)
// Roboter is the interface implemented by Robot that can send multiple types of messages.
type Roboter interface {
Send(interface{}) error
}
// Robot represents a workwxbot custom robot that can send messages to groups.
type Robot struct {
Webhook string
}
// NewRobot returns a roboter that can send messages.
func NewRobot(webhook string) Roboter {
return Robot{Webhook: webhook}
}
// SendMarkdown send a markdown type message.
func (r Robot) Send(msg interface{}) error {
return r.send(msg)
}
type workRsp struct {
Errcode int
Errmsg string
}
func (r Robot) send(msg interface{}) error {
m, err := json.Marshal(msg)
if err != nil {
return err
}
resp, err := http.Post(r.Webhook, "application/json", bytes.NewReader(m))
if err != nil {
return err
}
defer resp.Body.Close()
data, err := ioutil.ReadAll(resp.Body)
if err != nil {
return err
}
var wsp workRsp
err = json.Unmarshal(data, &wsp)
if err != nil {
return err
}
if wsp.Errcode != 0 {
return fmt.Errorf("wechatrobot send failed: %v", wsp.Errmsg)
}
return nil
}