/
chat.go
76 lines (63 loc) · 1.3 KB
/
chat.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
package slack
import (
"context"
"errors"
"github.com/nlopes/slack"
"gomodules.xyz/envconfig"
"gomodules.xyz/notify"
)
const UID = "slack"
type Options struct {
AuthToken string `envconfig:"AUTH_TOKEN" required:"true"`
Channel []string `envconfig:"CHANNEL"`
}
type client struct {
opt Options
body string
}
var _ notify.ByChat = &client{}
func New(opt Options) *client {
return &client{opt: opt}
}
func Default() (*client, error) {
var opt Options
err := envconfig.Process(UID, &opt)
if err != nil {
return nil, err
}
return New(opt), nil
}
func Load(loader envconfig.LoaderFunc) (*client, error) {
var opt Options
err := envconfig.Load(UID, &opt, loader)
if err != nil {
return nil, err
}
return New(opt), nil
}
func (c client) UID() string {
return UID
}
func (c client) WithBody(body string) notify.ByChat {
c.body = body
return &c
}
func (c client) To(to string, cc ...string) notify.ByChat {
c.opt.Channel = append([]string{to}, cc...)
return &c
}
func (c *client) Send() error {
if len(c.opt.Channel) == 0 {
return errors.New("missing to")
}
s := slack.New(c.opt.AuthToken)
for _, channel := range c.opt.Channel {
if _, _, err := s.PostMessageContext(
context.TODO(),
channel,
slack.MsgOptionText(c.body, false)); err != nil {
return err
}
}
return nil
}