Skip to content

Commit

Permalink
support to post in thread (#6)
Browse files Browse the repository at this point in the history
* support to post in thread

* specify thread timestamp and reply broadcast flag as context value

---------

Co-authored-by: Samuel Berthe <dev@samuel-berthe.fr>
  • Loading branch information
goro9 and samber authored May 5, 2024
1 parent 9c3c824 commit 62f5ebe
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 0 deletions.
29 changes: 29 additions & 0 deletions context.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
package slogslack

import "context"

type threadTimestampCtxKey struct{}

// reply in thread to posts with timestamps set this
func WithThreadTimestamp(ctx context.Context, ts string) context.Context {
return context.WithValue(ctx, threadTimestampCtxKey{}, ts)
}

func ContextThreadTimestamp(ctx context.Context) string {
if v, ok := ctx.Value(threadTimestampCtxKey{}).(string); ok {
return v
}
return ""
}

type replyBroadcastCtxKey struct{}

// broadcast to channel when replies to thread if set
func WithReplyBroadcast(ctx context.Context) context.Context {
return context.WithValue(ctx, replyBroadcastCtxKey{}, true)
}

func ContextReplyBroadcast(ctx context.Context) bool {
_, ok := ctx.Value(replyBroadcastCtxKey{}).(bool)
return ok
}
21 changes: 21 additions & 0 deletions handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,13 @@ func (h *SlackHandler) Handle(ctx context.Context, record slog.Record) error {
message.IconURL = h.option.IconURL
}

if ts := ContextThreadTimestamp(ctx); ts != "" {
message.ThreadTimestamp = ts
if ContextReplyBroadcast(ctx) {
message.ReplyBroadcast = true
}
}

go func() {
_ = h.postMessage(ctx, message)
}()
Expand Down Expand Up @@ -123,6 +130,20 @@ func (h *SlackHandler) postMessage(ctx context.Context, message *slack.WebhookMe
return slack.PostWebhookContext(ctx, h.option.WebhookURL, message)
}

options := []slack.MsgOption{
slack.MsgOptionText(message.Text, true),
slack.MsgOptionAttachments(message.Attachments...),
slack.MsgOptionUsername(message.Username),
slack.MsgOptionIconURL(message.IconURL),
slack.MsgOptionIconEmoji(message.IconEmoji),
}
if message.ThreadTimestamp != "" {
options = append(options, slack.MsgOptionTS(message.ThreadTimestamp))
}
if message.ReplyBroadcast {
options = append(options, slack.MsgOptionBroadcast())

Check failure on line 144 in handler.go

View workflow job for this annotation

GitHub Actions / lint

ineffectual assignment to options (ineffassign)
}

_, _, err := slack.
New(h.option.BotToken).
PostMessageContext(
Expand Down

0 comments on commit 62f5ebe

Please sign in to comment.