-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathnotifier.go
76 lines (66 loc) · 1.34 KB
/
notifier.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 hoi
import (
"fmt"
"io/ioutil"
"net/http"
"net/url"
"github.com/nlopes/slack"
)
const template = "Hi, you got a message from @%s\n%s"
type Notifier interface {
Notify(to, message string) error
}
func NewNotifier(conf Notification) Notifier {
switch conf.To {
case "slack":
return &SlackNotifier{
From: conf.From,
Client: slack.New(conf.Token),
}
case "takosan":
return &TakosanNotifier{
From: conf.From,
Host: conf.Host,
Port: conf.Port,
}
default:
return nil
}
}
type SlackNotifier struct {
From string
Client *slack.Client
}
func (s SlackNotifier) Notify(to, message string) error {
_, _, err := s.Client.PostMessage(
to,
fmt.Sprintf(template, s.From, message),
slack.PostMessageParameters{
Username: s.From,
},
)
if err != nil {
return fmt.Errorf("Failed to send message to %s: %s", to, err)
}
return nil
}
type TakosanNotifier struct {
From string
Host string
Port int
}
func (t TakosanNotifier) Notify(to, message string) error {
res, err := http.PostForm(
fmt.Sprintf("http://%s:%d/privmsg", t.Host, t.Port),
url.Values{"channel": {to}, "message": {fmt.Sprintf(template, t.From, message)}},
)
if err != nil {
return err
}
body, _ := ioutil.ReadAll(res.Body)
defer res.Body.Close()
if res.StatusCode == http.StatusBadRequest {
return fmt.Errorf("%s", body)
}
return nil
}