-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathslack.go
304 lines (259 loc) · 7.41 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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
package main
import (
"context"
"errors"
"fmt"
"strings"
"time"
"github.com/google/go-cmp/cmp"
"github.com/google/go-cmp/cmp/cmpopts"
"github.com/matryer/try"
"github.com/PagerDuty/go-pagerduty"
"github.com/slack-go/slack"
)
type slackUsers []slackUser
func (users slackUsers) findByPDUser(pdUser pagerduty.User) *slackUser {
// check email match first since it's a distinctive identifier
for _, slackUser := range users {
if slackUser.email == pdUser.Email {
return &slackUser
}
}
// if we couldn't find an email match, use name. this is the second choice as name is not unique in an organization
for _, slackUser := range users {
if slackUser.realName == strings.ToLower(pdUser.Name) ||
slackUser.name == strings.ToLower(pdUser.Name) {
return &slackUser
}
}
return nil
}
type slackUser struct {
id string
name string
realName string
email string
}
type channelList []slack.Channel
func (cl channelList) find(id, name string) *slack.Channel {
if id == "" && name == "" {
return nil
}
for _, ch := range cl {
if ch.ID == id || ch.Name == name {
return &ch
}
}
return nil
}
type slackMetaClient struct {
slackClient *slack.Client
channelTypes []string
}
func newSlackMetaClient(token string, includePrivateChannels bool) *slackMetaClient {
channelTypes := []string{"public_channel"}
if includePrivateChannels {
channelTypes = append(channelTypes, "private_channel")
}
return &slackMetaClient{
slackClient: slack.New(token),
channelTypes: channelTypes,
}
}
func (metaClient *slackMetaClient) getSlackUsers(ctx context.Context) (slackUsers, error) {
// GetUsersContext retries on rate-limit errors, so no need to wrap it around
// retryOnSlackRateLimit.
apiUsers, err := metaClient.slackClient.GetUsersContext(ctx)
if err != nil {
return nil, err
}
slUsers := make(slackUsers, 0, len(apiUsers))
for _, apiUser := range apiUsers {
// Ignore non-human users.
if apiUser.Deleted || apiUser.IsBot {
continue
}
slUsers = append(slUsers, createSlackUser(apiUser))
}
return slUsers, nil
}
func (metaClient *slackMetaClient) getChannels(ctx context.Context) (channelList, error) {
var (
list channelList
cursor string
)
for {
var (
channels []slack.Channel
nextCursor string
)
retErr := retryOnSlackRateLimit(ctx, func(ctx context.Context) error {
var err error
channels, nextCursor, err = metaClient.slackClient.GetConversationsContext(ctx, &slack.GetConversationsParameters{
Cursor: cursor,
ExcludeArchived: true,
Limit: 200,
Types: metaClient.channelTypes,
})
return err
})
if retErr != nil {
return nil, retErr
}
for _, channel := range channels {
list = append(list, channel)
}
if nextCursor == "" {
break
}
cursor = nextCursor
}
return list, nil
}
func (metaClient *slackMetaClient) getChannelByID(ctx context.Context, id string) (*slack.Channel, error) {
return metaClient.slackClient.GetConversationInfoContext(ctx, &slack.GetConversationInfoInput{
ChannelID: id,
})
}
func (metaClient *slackMetaClient) getUserGroups(ctx context.Context) ([]UserGroup, error) {
var groups []slack.UserGroup
retErr := retryOnSlackRateLimit(ctx, func(ctx context.Context) error {
var err error
groups, err = metaClient.slackClient.GetUserGroupsContext(ctx, []slack.GetUserGroupsOption(nil)...)
return err
})
if retErr != nil {
return nil, retErr
}
userGroups := make([]UserGroup, 0, len(groups))
for _, group := range groups {
userGroups = append(userGroups, UserGroup{
ID: group.ID,
Name: group.Name,
Handle: group.Handle,
})
}
return userGroups, nil
}
type oncallGroups []*oncallGroup
func (ocgs *oncallGroups) getOrCreate(ug UserGroup) *oncallGroup {
for _, ocg := range *ocgs {
if ocg.userGroupID == ug.ID {
return ocg
}
}
ocg := &oncallGroup{
userGroupID: ug.ID,
userGroupName: ug.Name,
}
*ocgs = append(*ocgs, ocg)
return ocg
}
type oncallGroup struct {
userGroupID string
userGroupName string
members []string
}
func (ocg *oncallGroup) ensureMember(m string) {
for _, memb := range ocg.members {
if memb == m {
return
}
}
ocg.members = append(ocg.members, m)
}
func (metaClient *slackMetaClient) joinChannel(ctx context.Context, channelID string) (joined bool, err error) {
_, warn, respWarnings, err := metaClient.slackClient.JoinConversationContext(ctx, channelID)
if err != nil {
if strings.Contains(err.Error(), "method_not_supported_for_channel_type") {
// This likely means it is a private channel that we cannot join.
return false, nil
}
return false, err
}
const alreadyInChannelWarning = "already_in_channel"
joined = true
var warnings []string
for _, w := range append([]string{warn}, respWarnings...) {
if w != "" {
if w == alreadyInChannelWarning {
joined = false
continue
}
warnings = append(warnings, warn)
}
}
if len(warnings) > 0 {
return false, fmt.Errorf("joined channel with warnings: %s", strings.Join(warnings, "; "))
}
return joined, nil
}
func (metaClient *slackMetaClient) updateOncallGroupMembers(ctx context.Context, oncallGroups oncallGroups, dryRun bool) error {
for _, group := range oncallGroups {
currentMembers, err := metaClient.slackClient.GetUserGroupMembersContext(ctx, group.userGroupID)
if err != nil {
return fmt.Errorf("failed to get user group members for %q: %s", group.userGroupName, err)
}
if cmp.Equal(currentMembers, group.members, cmpopts.SortSlices(func(x, y string) bool {
return x < y
})) {
fmt.Printf("User group %q already has the right members\n", group.userGroupName)
continue
}
concatMembers := strings.Join(group.members, ",")
if dryRun {
fmt.Printf("[DRY RUN] Not updating user group %s with member(s): %s\n", group.userGroupName, concatMembers)
continue
}
_, err = metaClient.slackClient.UpdateUserGroupMembersContext(ctx, group.userGroupID, concatMembers)
if err != nil {
return fmt.Errorf("failed to update user group members for %q: %s", group.userGroupName, err)
}
fmt.Printf("Updated user group %s with member(s): %s\n", group.userGroupName, concatMembers)
}
return nil
}
func (metaClient *slackMetaClient) updateTopic(ctx context.Context, channelID string, topic string, dryRun bool) error {
channel, err := metaClient.getChannelByID(ctx, channelID)
if err != nil {
return err
}
if channel.Topic.Value == topic {
fmt.Println("Topic already set correctly")
} else {
fmt.Printf("Updating topic from\n[BEGIN-OF-OLD]\n%s\n[END-OF-OLD]\nto:\n[BEGIN-OF-NEW]\n%s\n[END-OF-NEW]\n", channel.Topic.Value, topic)
if dryRun {
fmt.Println("[DRY RUN] Not updating topic")
return nil
}
_, err := metaClient.slackClient.SetTopicOfConversationContext(ctx, channel.ID, topic)
if err != nil {
return err
}
fmt.Println("Topic updated")
}
return nil
}
func createSlackUser(apiUser slack.User) slackUser {
return slackUser{
id: apiUser.ID,
name: strings.ToLower(apiUser.Name),
realName: strings.ToLower(apiUser.RealName),
email: apiUser.Profile.Email,
}
}
func retryOnSlackRateLimit(ctx context.Context, f func(ctx context.Context) error) error {
return try.Do(func(attempt int) (retry bool, retryErr error) {
err := f(ctx)
if err != nil {
var rle *slack.RateLimitedError
if errors.As(err, &rle) {
sleep := rle.RetryAfter
fmt.Printf("Slack rate limit hit -- waiting %s\n", sleep)
time.Sleep(sleep)
return true, err
}
}
return false, err
})
}