forked from slack-io/slacker
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathresponse.go
85 lines (68 loc) · 2.05 KB
/
response.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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
package slacker
import (
"fmt"
"log"
"github.com/slack-go/slack"
)
const (
errorFormat = "*Error:* _%s_"
)
// A ResponseWriter interface is used to respond to an event
type ResponseWriter interface {
Post(channel string, message string, options ...ReplyOption) error
Reply(text string, options ...ReplyOption) error
ReportError(err error, options ...ReportErrorOption)
}
// NewResponse creates a new response structure
func NewResponse(botCtx BotContext) ResponseWriter {
return &response{botCtx: botCtx}
}
type response struct {
botCtx BotContext
}
// ReportError sends back a formatted error message to the channel where we received the event from
func (r *response) ReportError(err error, options ...ReportErrorOption) {
defaults := NewReportErrorDefaults(options...)
apiClient := r.botCtx.APIClient()
event := r.botCtx.Event()
opts := []slack.MsgOption{
slack.MsgOptionText(fmt.Sprintf(errorFormat, err.Error()), false),
}
if defaults.ThreadResponse {
opts = append(opts, slack.MsgOptionTS(event.TimeStamp))
}
_, _, err = apiClient.PostMessage(event.ChannelID, opts...)
if err != nil {
log.Printf("failed posting message: %v\n", err)
}
}
// Reply send a message to the current channel
func (r *response) Reply(message string, options ...ReplyOption) error {
ev := r.botCtx.Event()
if ev == nil {
return fmt.Errorf("unable to get message event details")
}
return r.Post(ev.ChannelID, message, options...)
}
// Post send a message to a channel
func (r *response) Post(channel string, message string, options ...ReplyOption) error {
defaults := NewReplyDefaults(options...)
apiClient := r.botCtx.APIClient()
event := r.botCtx.Event()
if event == nil {
return fmt.Errorf("unable to get message event details")
}
opts := []slack.MsgOption{
slack.MsgOptionText(message, false),
slack.MsgOptionAttachments(defaults.Attachments...),
slack.MsgOptionBlocks(defaults.Blocks...),
}
if defaults.ThreadResponse {
opts = append(opts, slack.MsgOptionTS(event.TimeStamp))
}
_, _, err := apiClient.PostMessage(
channel,
opts...,
)
return err
}