slack-bot/pkg/notify/slack.go

71 lines
1.5 KiB
Go
Raw Normal View History

2021-03-21 23:17:15 +00:00
package notify
import (
2021-03-22 02:39:42 +00:00
"context"
2021-03-21 23:17:15 +00:00
"fmt"
"log"
"github.com/slack-go/slack"
)
2021-03-22 02:39:42 +00:00
type SlackContextKey string
const (
slackHookBaseURL = "hooks.slack.com/services"
DryRunContextKey SlackContextKey = "dryRun"
)
2021-03-21 23:17:15 +00:00
//Notifier interface represent mean to send notification
type Notifier interface {
Notify(message string)
}
//Message store and represent alerting message
type Message struct {
ShouldNotify bool
Content string
}
type SlackNotifier struct {
BotID string
DestChannelID string
WebhookID string
}
//NewSlackNotifier create slack notifier
func NewSlackNotifier(BotID, DestChannelID, WebhookID string) *SlackNotifier {
return &SlackNotifier{
BotID: BotID,
DestChannelID: DestChannelID,
WebhookID: WebhookID,
}
}
//Notify send notification to channel
func (sn *SlackNotifier) Notify(ctx context.Context, messages ...Message) {
shouldNotify := false
var content string
for _, message := range messages {
if message.ShouldNotify {
shouldNotify = true
content = fmt.Sprintf("%s\n%s", content, message.Content)
}
}
if shouldNotify {
2021-03-21 23:17:15 +00:00
msg := &slack.WebhookMessage{
Text: content,
2021-03-21 23:17:15 +00:00
}
url := fmt.Sprintf("https://%s/%s/%s/%s", slackHookBaseURL, sn.BotID, sn.DestChannelID, sn.WebhookID)
2021-03-22 02:39:42 +00:00
if v := ctx.Value(DryRunContextKey); v != nil && v == true {
log.Printf("dryrun mode : slack notify to %s\n", url)
log.Printf("dryrun mode : %+v\n", msg)
} else {
err := slack.PostWebhook(url, msg)
if err != nil {
log.Printf("Send message error %+v", err)
}
2021-03-21 23:17:15 +00:00
}
}
}