forked from sourcegraph/sourcegraph-public-snapshot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathslack.go
78 lines (68 loc) · 2.61 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
69
70
71
72
73
74
75
76
77
78
package main
import (
"context"
"fmt"
"github.com/inconshreveable/log15"
"github.com/sourcegraph/sourcegraph/internal/api"
"github.com/sourcegraph/sourcegraph/internal/slack"
)
func (n *notifier) slackNotify(ctx context.Context) {
plural := ""
if n.results.Data.Search.Results.ApproximateResultCount != "1" {
plural = "s"
}
text := fmt.Sprintf(`*%s* new result%s found for saved search <%s|"%s">`,
n.results.Data.Search.Results.ApproximateResultCount,
plural,
searchURL(n.newQuery, utmSourceSlack),
n.query.Description,
)
for _, recipient := range n.recipients {
if err := slackNotify(ctx, recipient, text, n.query.SlackWebhookURL); err != nil {
log15.Error("Failed to post Slack notification message.", "recipient", recipient, "text", text, "error", err)
}
}
// TODO(Dan): find all users in the recipient list and log events for all of them
logEvent(0, "SavedSearchSlackNotificationSent", "results")
}
func slackNotifySubscribed(ctx context.Context, recipient *recipient, query api.SavedQuerySpecAndConfig) error {
text := fmt.Sprintf(`Slack notifications enabled for the saved search <%s|"%s">. Notifications will be sent here when new results are available.`,
searchURL(query.Config.Query, utmSourceSlack),
query.Config.Description,
)
if err := slackNotify(ctx, recipient, text, query.Config.SlackWebhookURL); err != nil {
return err
}
// TODO(Dan): find all users in the recipient list and log events for all of them
logEvent(0, "SavedSearchSlackNotificationSent", "enabled")
return nil
}
func slackNotifyUnsubscribed(ctx context.Context, recipient *recipient, query api.SavedQuerySpecAndConfig) error {
text := fmt.Sprintf(`Slack notifications for the saved search <%s|"%s"> disabled.`,
searchURL(query.Config.Query, utmSourceSlack),
query.Config.Description,
)
if err := slackNotify(ctx, recipient, text, query.Config.SlackWebhookURL); err != nil {
return err
}
// TODO(Dan): find all users in the recipient list and log events for all of them
logEvent(0, "SavedSearchSlackNotificationSent", "disabled")
return nil
}
func slackNotify(ctx context.Context, recipient *recipient, text string, slackWebhookURL *string) error {
if !recipient.slack {
return nil
}
if slackWebhookURL == nil || *slackWebhookURL == "" {
return fmt.Errorf("unable to send Slack notification because recipient (%s) has no Slack webhook URL configured", recipient.spec)
}
payload := &slack.Payload{
Username: "saved-search-bot",
IconEmoji: ":mag:",
UnfurlLinks: false,
UnfurlMedia: false,
Text: text,
}
client := slack.New(*slackWebhookURL, true)
return slack.Post(payload, client.WebhookURL)
}