-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
189 lines (160 loc) · 5.22 KB
/
main.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
package main
import (
"fmt"
"log"
"math/rand"
"os"
"strings"
"time"
"github.com/Clever/kayvee-go/logger"
"github.com/Clever/pickabot/github"
"github.com/Clever/pickabot/slackapi"
"github.com/slack-go/slack"
discovery "gopkg.in/Clever/discovery-go.v1"
whoswho "github.com/Clever/who-is-who/go-client"
)
var lg = logger.New("pickabot")
// SlackLoop is the endless service loop pickabot remains in after startup --
// e.g. the steady-state of the bot.
func SlackLoop(s *Bot) {
s.Logger.InfoD("start", logger.M{"message": "Starting up"})
rtm := s.SlackAPIService.NewRTM()
s.SlackRTMService = &slackapi.SlackRTMServer{Rtm: rtm}
go rtm.ManageConnection()
Loop:
for {
/* Refresh the user/team cache every 1-hour -- We could do this in a separate goroutine that
updates the cache on a separate thread every sixty minutes. But, this explodes complexity by
adding race conditions, etc. and yet still wouldn't handle the case where a command is attempted
after a user is deactivated but before the cache refreshes. */
if time.Since(s.LastCacheRefresh) > 60*time.Minute {
teams, overrides, userFlair, err := buildTeams(s.WhoIsWhoClient)
if err != nil {
s.Logger.CriticalD("user cache refresh failed. will continue without cache refresh...", logger.M{"error": err})
} else {
s.TeamToTeamMembers = teams
s.TeamOverrides = overrides
s.UserFlair = userFlair
s.LastCacheRefresh = time.Now()
}
}
select {
case msg := <-rtm.IncomingEvents: // listening for slack events via the slack real-time messaging api
switch ev := msg.Data.(type) { // extract the type of the slack event
case *slack.MessageEvent:
s.DecodeMessage(ev)
case *slack.RTMError:
s.Logger.CriticalD("listening", logger.M{"error": ev.Error()})
case *slack.ConnectionErrorEvent:
s.Logger.CriticalD("listening", logger.M{"error": ev.Error()})
case *slack.InvalidAuthEvent:
s.Logger.CriticalD("listening", logger.M{"error": "invalid credentials"})
break Loop
default:
// Ignore other events..
}
}
}
}
func requireEnvVar(s string) string {
val := os.Getenv(s)
if val == "" {
log.Fatalf("env var %s is not defined", s)
}
return val
}
func main() {
api := slack.New(
requireEnvVar("SLACK_ACCESS_TOKEN"),
slack.OptionLog(log.New(os.Stdout, "pickabot: ", log.Lshortfile|log.LstdFlags)),
slack.OptionDebug(false),
)
endpoint, err := discovery.URL("who-is-who", "default")
if err != nil {
log.Fatalf("who-is-who discovery error: %s", err)
}
client := whoswho.NewClient(endpoint)
teams, overrides, userFlair, err := buildTeams(client) // populate a cached set of teams and their members
if err != nil {
log.Fatalf("error building teams: %s", err)
}
appID := requireEnvVar("GITHUB_APP_ID")
installationID := requireEnvVar("GITHUB_INSTALLATION_ID")
devMode := requireEnvVar("DEV_MODE") != "false"
githubOrg := requireEnvVar("GITHUB_ORG_NAME")
githubPrivateKey := requireEnvVar("GITHUB_PRIVATE_KEY")
privateKeyBytes := []byte(githubPrivateKey)
githubClient := &github.AppClient{
AppID: appID,
InstallationID: installationID,
Logger: lg,
PrivateKey: privateKeyBytes,
}
if err != nil {
log.Fatalf("error setting up github client: %s", err)
}
pickabot := &Bot{
DevMode: devMode,
GithubClient: githubClient,
GithubOrgName: githubOrg,
SlackAPIService: &slackapi.SlackAPIServer{Api: api},
Logger: lg,
Name: requireEnvVar("BOT_NAME"),
RandomSource: rand.NewSource(time.Now().UnixNano()),
UserFlair: userFlair,
TeamOverrides: overrides,
TeamToTeamMembers: teams,
WhoIsWhoClient: client,
LastCacheRefresh: time.Now(),
}
// The below code is just prints out the teams and their members for debugging purposes and as a sanity check
for teamName := range teams {
fmt.Printf("team=%s has members: ", teamName)
users := pickabot.buildTeam(teamName)
userText := []string{}
for _, u := range users {
userText = append(userText, fmt.Sprintf("%s %s (%s)", u.FirstName, u.LastName, u.SlackID))
}
fmt.Println(strings.Join(userText, ", "))
}
SlackLoop(pickabot)
}
// This method uses the who-is-who go client to populate the set of teams and their members
func buildTeams(client whoIsWhoClientIface) (map[string][]whoswho.User, []Override, map[string]string, error) {
users, err := client.GetUserList()
if err != nil {
return nil, []Override{}, map[string]string{}, err
}
// fetch users from who-is-who
overrides := []Override{}
teams := map[string][]whoswho.User{}
userFlair := map[string]string{}
for _, u := range users {
if !u.Active {
continue
}
// Add overrides from who-is-who
for _, to := range u.Pickabot.TeamOverrides {
overrides = append(overrides, Override{
User: u,
Team: to.Team,
Include: to.Include,
})
}
// Add flair
if u.Pickabot.Flair != "" {
userFlair[u.SlackID] = u.Pickabot.Flair
}
if !(strings.HasPrefix(u.Team, "Engineering - ") && u.Active) {
continue
}
// Format the team name
split := strings.Split(u.Team, " - ")
team := split[1]
team = strings.ToLower(team)
team = strings.ReplaceAll(team, " ", "-")
// Write user to teams
teams[team] = append(teams[team], u)
}
return teams, overrides, userFlair, nil
}