/
slack.go
68 lines (59 loc) · 1.57 KB
/
slack.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
package client
import (
"context"
"fmt"
"github.com/chitoku-k/slack-to-ssh/service"
"github.com/slack-go/slack"
)
type slackInteractionResponder struct {
Actions []service.SlackAction
Client *slack.Client
}
func NewSlackInteractionResponder(actions []service.SlackAction) service.InteractionResponder {
return &slackInteractionResponder{
Actions: actions,
Client: slack.New(""),
}
}
func (sir *slackInteractionResponder) Execute(ctx context.Context, response service.SlackInteractionResponse) error {
var action *service.SlackAction
for _, v := range sir.Actions {
if v.Name == response.ActionName {
action = &v
break
}
}
if action == nil {
return fmt.Errorf("failed to find suitable action: %s", response.ActionName)
}
options := []slack.MsgOption{
slack.MsgOptionResponseURL(response.ResponseURL, slack.ResponseTypeInChannel),
}
for _, attachment := range response.Message.Attachments {
if response.Error != nil {
attachment.Color = "danger"
attachment.Text = response.Error.Error()
} else {
attachment.Color = "good"
attachment.Text = action.AttachmentText
}
if response.Body != nil {
attachment.MarkdownIn = []string{"fields"}
attachment.Fields = []slack.AttachmentField{
{Value: fmt.Sprintf("```\n%s\n```", response.Body)},
}
} else {
attachment.Fields = nil
}
options = append(options, slack.MsgOptionAttachments(attachment))
}
_, _, _, err := sir.Client.SendMessageContext(
ctx,
response.Message.Channel,
options...,
)
if err != nil {
return fmt.Errorf("failed to send response: %w", err)
}
return nil
}