bbgo_origin/pkg/notifier/slacknotifier/slack.go

213 lines
4.6 KiB
Go
Raw Normal View History

2020-09-19 01:05:06 +00:00
package slacknotifier
import (
"bytes"
2020-09-19 01:05:06 +00:00
"context"
"fmt"
"time"
2020-09-19 01:05:06 +00:00
"golang.org/x/time/rate"
"github.com/c9s/bbgo/pkg/livenote"
"github.com/c9s/bbgo/pkg/types"
2020-10-28 09:34:12 +00:00
log "github.com/sirupsen/logrus"
2020-09-19 01:05:06 +00:00
"github.com/slack-go/slack"
)
var limiter = rate.NewLimiter(rate.Every(1*time.Second), 3)
type notifyTask struct {
Channel string
Opts []slack.MsgOption
}
2020-09-19 01:05:06 +00:00
type Notifier struct {
2020-10-22 02:47:54 +00:00
client *slack.Client
channel string
taskC chan notifyTask
2024-11-05 09:34:26 +00:00
liveNotePool *livenote.Pool
2020-09-19 01:05:06 +00:00
}
type NotifyOption func(notifier *Notifier)
2022-01-16 11:06:26 +00:00
func New(client *slack.Client, channel string, options ...NotifyOption) *Notifier {
2020-09-19 01:05:06 +00:00
notifier := &Notifier{
2024-11-05 09:34:26 +00:00
channel: channel,
client: client,
taskC: make(chan notifyTask, 100),
liveNotePool: livenote.NewPool(100),
2020-09-19 01:05:06 +00:00
}
for _, o := range options {
o(notifier)
}
go notifier.worker()
2020-09-19 01:05:06 +00:00
return notifier
}
func (n *Notifier) worker() {
ctx := context.Background()
for {
select {
case <-ctx.Done():
return
case task := <-n.taskC:
// ignore the wait error
_ = limiter.Wait(ctx)
_, _, err := n.client.PostMessageContext(ctx, task.Channel, task.Opts...)
if err != nil {
log.WithError(err).
WithField("channel", task.Channel).
Errorf("slack api error: %s", err.Error())
}
}
}
}
func (n *Notifier) PostLiveNote(obj livenote.Object) error {
2024-11-05 09:34:26 +00:00
note := n.liveNotePool.Update(obj)
ctx := context.Background()
channel := note.ChannelID
if channel == "" {
channel = n.channel
}
2024-11-05 09:34:26 +00:00
var attachment slack.Attachment
if creator, ok := note.Object.(types.SlackAttachmentCreator); ok {
attachment = creator.SlackAttachment()
} else {
return fmt.Errorf("livenote object does not support types.SlackAttachmentCreator interface")
}
opts := slack.MsgOptionAttachments(attachment)
if note.MessageID != "" {
// UpdateMessageContext returns channel, timestamp, text, err
2024-11-05 09:34:26 +00:00
_, _, _, err := n.client.UpdateMessageContext(ctx, channel, note.MessageID, opts)
if err != nil {
return err
}
} else {
2024-11-05 09:34:26 +00:00
respCh, respTs, err := n.client.PostMessageContext(ctx, channel, opts)
if err != nil {
log.WithError(err).
WithField("channel", n.channel).
Errorf("slack api error: %s", err.Error())
return err
}
note.SetChannelID(respCh)
note.SetMessageID(respTs)
}
return nil
}
func (n *Notifier) Notify(obj interface{}, args ...interface{}) {
// TODO: filter args for the channel option
n.NotifyTo(n.channel, obj, args...)
2020-10-22 02:47:54 +00:00
}
func filterSlackAttachments(args []interface{}) (slackAttachments []slack.Attachment, pureArgs []interface{}) {
var firstAttachmentOffset = -1
2020-09-19 01:05:06 +00:00
for idx, arg := range args {
switch a := arg.(type) {
// concrete type assert first
case slack.Attachment:
if firstAttachmentOffset == -1 {
firstAttachmentOffset = idx
2020-09-19 01:05:06 +00:00
}
slackAttachments = append(slackAttachments, a)
case *slack.Attachment:
if firstAttachmentOffset == -1 {
firstAttachmentOffset = idx
}
slackAttachments = append(slackAttachments, *a)
case types.SlackAttachmentCreator:
if firstAttachmentOffset == -1 {
firstAttachmentOffset = idx
2020-09-19 01:05:06 +00:00
}
slackAttachments = append(slackAttachments, a.SlackAttachment())
case types.PlainText:
if firstAttachmentOffset == -1 {
firstAttachmentOffset = idx
}
// fallback to PlainText if it's not supported
// convert plain text to slack attachment
text := a.PlainText()
slackAttachments = append(slackAttachments, slack.Attachment{
Title: text,
})
2020-09-19 01:05:06 +00:00
}
}
pureArgs = args
if firstAttachmentOffset > -1 {
pureArgs = args[:firstAttachmentOffset]
2020-09-19 01:05:06 +00:00
}
return slackAttachments, pureArgs
}
2020-09-19 01:05:06 +00:00
func (n *Notifier) NotifyTo(channel string, obj interface{}, args ...interface{}) {
if len(channel) == 0 {
channel = n.channel
}
slackAttachments, pureArgs := filterSlackAttachments(args)
var opts []slack.MsgOption
switch a := obj.(type) {
case string:
opts = append(opts, slack.MsgOptionText(fmt.Sprintf(a, pureArgs...), true),
slack.MsgOptionAttachments(slackAttachments...))
case slack.Attachment:
opts = append(opts, slack.MsgOptionAttachments(append([]slack.Attachment{a}, slackAttachments...)...))
case types.SlackAttachmentCreator:
// convert object to slack attachment (if supported)
opts = append(opts, slack.MsgOptionAttachments(append([]slack.Attachment{a.SlackAttachment()}, slackAttachments...)...))
default:
log.Errorf("slack message conversion error, unsupported object: %T %+v", a, a)
}
select {
case n.taskC <- notifyTask{
Channel: channel,
Opts: opts,
}:
case <-time.After(50 * time.Millisecond):
return
}
2020-09-19 01:05:06 +00:00
}
func (n *Notifier) SendPhoto(buffer *bytes.Buffer) {
n.SendPhotoTo(n.channel, buffer)
}
func (n *Notifier) SendPhotoTo(channel string, buffer *bytes.Buffer) {
// TODO
}