Skip to content
This repository has been archived by the owner on Aug 31, 2022. It is now read-only.

feature: slack receiver should use webhook instead of token #38

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 24 additions & 17 deletions pkg/sinks/slack.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,44 +2,41 @@ package sinks

import (
"context"

"github.com/nlopes/slack"
"github.com/opsgenie/kubernetes-event-exporter/pkg/kube"
"github.com/rs/zerolog/log"
)

type SlackConfig struct {
Token string `yaml:"token"`
Channel string `yaml:"channel"`
Message string `yaml:"message"`
Fields map[string]string `yaml:"fields"`
Endpoint string `yaml:endpoint`
Message string `yaml:"message"`
Fields map[string]string `yaml:"fields"`
}

type SlackSink struct {
cfg *SlackConfig
client *slack.Client
cfg *SlackConfig
}

func NewSlackSink(cfg *SlackConfig) (Sink, error) {
return &SlackSink{
cfg: cfg,
client: slack.New(cfg.Token),
cfg: cfg,
}, nil
}

func (s *SlackSink) Send(ctx context.Context, ev *kube.EnhancedEvent) error {
channel, err := GetString(ev, s.cfg.Channel)
message, err := GetString(ev, s.cfg.Message)
if err != nil {
return err
}

message, err := GetString(ev, s.cfg.Message)
endpoint, err := GetString(ev, s.cfg.Endpoint)
if err != nil {
return err
}

options := []slack.MsgOption{slack.MsgOptionText(message, true)}
fields := make([]slack.AttachmentField, 0)

if s.cfg.Fields != nil {
fields := make([]slack.AttachmentField, 0)
for k, v := range s.cfg.Fields {
fieldText, err := GetString(ev, v)
if err != nil {
Expand All @@ -52,12 +49,22 @@ func (s *SlackSink) Send(ctx context.Context, ev *kube.EnhancedEvent) error {
Short: false,
})
}
options = append(options, slack.MsgOptionAttachments(slack.Attachment{Fields: fields}))
}

_ch, _ts, _text, err := s.client.SendMessageContext(ctx, channel, options...)
log.Debug().Str("ch", _ch).Str("ts", _ts).Str("text", _text).Err(err).Msg("Slack Response")
return err
attachment := slack.Attachment{
Fields: fields,
}

webhookMessage := slack.WebhookMessage{
Text: message,
Attachments: []slack.Attachment{attachment},
}

err := slack.PostWebhook(endpoint, &webhookMessage)
if err != nil {
return err
}
return nil
}

func (s *SlackSink) Close() {
Expand Down