-
Notifications
You must be signed in to change notification settings - Fork 56
/
api.go
113 lines (103 loc) · 2.29 KB
/
api.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
package main
import (
"fmt"
"time"
"github.com/slack-go/slack"
)
var (
api *slack.Client
msgOpts = &slack.PostMessageParameters{AsUser: true}
)
// InitAPI for Slack
func InitAPI(token string) {
api = slack.New(token)
res, err := api.AuthTest()
failOnError(err, "Slack API Error")
output(fmt.Sprintf("connected to %s as %s", res.Team, res.User))
}
// Return list of all channels by name
func listChannels() (names []string) {
list, err := getConversations("public_channel", "private_channel")
failOnError(err)
for _, c := range list {
names = append(names, c.Name)
}
return names
}
// Return list of all groups by name
func listGroups() (names []string) {
list, err := getConversations("mpim")
failOnError(err)
for _, c := range list {
names = append(names, c.Name)
}
return names
}
// Return list of all ims by name
func listIms() (names []string) {
users, err := api.GetUsers()
failOnError(err)
list, err := getConversations("im")
failOnError(err)
for _, c := range list {
for _, u := range users {
if u.ID == c.User {
names = append(names, u.Name)
continue
}
}
}
return names
}
// Lookup Slack id for channel, group, or im by name
func lookupSlackID(name string) string {
list, err := getConversations("public_channel", "private_channel", "mpim")
if err == nil {
for _, c := range list {
if c.Name == name {
return c.ID
}
}
}
users, err := api.GetUsers()
if err == nil {
list, err := getConversations("im")
if err == nil {
for _, c := range list {
for _, u := range users {
if u.Name == name && u.ID == c.User {
return c.ID
}
}
}
}
}
exitErr(fmt.Errorf("No such channel, group, or im"))
return ""
}
func getConversations(types ...string) (list []slack.Channel, err error) {
cursor := ""
for {
param := &slack.GetConversationsParameters{
Cursor: cursor,
ExcludeArchived: "true",
Types: types,
Limit: 1000,
}
channels, cur, err := api.GetConversations(param)
if err != nil {
if rateLimitedError, ok := err.(*slack.RateLimitedError); ok {
output(fmt.Sprintf("%v", rateLimitedError))
time.Sleep(rateLimitedError.RetryAfter)
continue
}
return list, err
}
list = append(list, channels...)
if cur == "" {
break
}
cursor = cur
}
return list, nil
}