-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
242 lines (216 loc) · 5.45 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
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
package main
import (
"fmt"
"log"
"os"
"github.com/hashicorp/golang-lru"
"github.com/microamp/slacko/config"
"github.com/microamp/slacko/utils"
"github.com/nlopes/slack"
)
const (
configFile = "slacko.json"
envVarSlackAPIToken = "SLACK_API_TOKEN"
)
var cache *lru.Cache // LRU cache
// Filter out irrelevant request messages
func filterRequests(unfiltered <-chan *utils.MessageContext, filtered chan<- *utils.MessageContext) {
for {
mc, ok := <-unfiltered
if !ok {
mc.Printf("Error receiving from channel\n")
}
sInfo, err := mc.GetInfo()
if err != nil {
mc.Printf("Error retrieving message info: %v\n", err)
continue
}
mc.Printf("Message before filter: %s\n", sInfo)
// Ignore messages from bots (including @slacko itself)
// unless it's edited (no user)
if !mc.MsgEdited {
isBot, err := mc.IsBot()
if err != nil {
mc.Printf("Error getting user info: %v\n", err)
continue
}
if isBot {
mc.Printf("Ignoring message from other bots\n")
continue
}
}
// Ignore messages unless starting with '@slacko: '
replyToID := mc.ExtractReplyToID()
if replyToID == "" {
mc.Printf("Ignoring message without '@<user>: ' prefix\n")
continue
}
replyToInfo, err := mc.GetUserInfo(replyToID)
if err != nil {
mc.Printf("Error getting user info: %v\n", err)
continue
}
if replyToInfo.Name != mc.BotName {
mc.Printf("%s is not %s\n", replyToInfo.Name, mc.BotName)
continue
}
mc.ReplyToID = replyToID
filtered <- mc
}
}
// Build response messages
func buildResponses(filtered <-chan *utils.MessageContext, gpClient utils.GoPlaygroundClient) {
for {
mc, ok := <-filtered
if !ok {
mc.Printf("Error receiving from channel\n")
continue
}
sInfo, err := mc.GetInfo()
if err != nil {
mc.Printf("Error retrieving message info: %v\n", err)
continue
}
mc.Printf("Message after filter: %s\n", sInfo)
params := slack.PostMessageParameters{
Username: mc.BotName,
AsUser: true,
}
// Ignore all non-code messages
code := mc.ExtractCode(mc.ReplyToID)
if code == "" {
_, ts, err := mc.PostMessage(
mc.MsgChannel,
fmt.Sprintf("Error: %s\n", "No code received. Accepted formats are\n"+
"`single-line code`\n"+
"```multi-line code```"),
params,
)
if err != nil {
mc.Printf("Error posting message: %v\n", err)
continue
}
go cache.Add(mc.MsgTimestamp, ts)
continue
}
// Compile code via Go Playground
result, err := gpClient.Compile(code)
// Post unexpected error
if err != nil {
_, ts, err := mc.PostMessage(
mc.MsgChannel,
fmt.Sprintf("Error compiling: %v\n", err),
params,
)
if err != nil {
mc.Printf("Error posting message: %v\n", err)
continue
}
go cache.Add(mc.MsgTimestamp, ts)
continue
}
// Post compile errors from Go Playground
if result.CompileErrors != "" {
_, ts, err := mc.PostMessage(
mc.MsgChannel,
fmt.Sprintf("Compile errors from Go Playground: %s", result.CompileErrors),
params,
)
if err != nil {
mc.Printf("Error posting message: %v\n", err)
continue
}
go cache.Add(mc.MsgTimestamp, ts)
continue
}
resultOutput := result.GetOutput()
// Check if edited
if mc.MsgEdited {
// Check if cached
if cache.Contains(mc.MsgTimestamp) {
cached, ok := cache.Get(mc.MsgTimestamp)
if !ok {
mc.Printf("Error updating message: %v\n", err)
continue
}
// Update previous result
_, _, _, err = mc.UpdateMessage(
mc.MsgChannel,
cached.(string),
resultOutput,
)
if err != nil {
mc.Printf("Error updating message: %v\n", err)
continue
}
}
} else {
// Post new result
_, ts, err := mc.PostMessage(
mc.MsgChannel,
resultOutput,
params,
)
if err != nil {
mc.Printf("Error posting message: %v\n", err)
continue
}
go cache.Add(mc.MsgTimestamp, ts)
}
}
}
func main() {
// Validate environment variable, SLACK_API_TOKEN
slackAPIToken := os.Getenv(envVarSlackAPIToken)
if slackAPIToken == "" {
panic("API token not provided (env var: SLACK_API_TOKEN)")
}
// Validate config settings
config, err := config.ReadConfig(configFile)
if err != nil {
panic(fmt.Sprintf("Error reading config (filename: %s): %v", configFile, err))
}
if config.GoPlaygroundHost == "" {
panic("'GoPlaygroundHost' must be provided. Check your config.")
}
if config.BotName == "" {
panic("'BotName' must be provided. Check your config.")
}
// Create LRU cache
cache, err = lru.New(config.CacheSize)
if err != nil {
panic(fmt.Sprintf("Cannot create LRU cache: %v", err))
}
api := slack.New(slackAPIToken)
api.SetDebug(config.DebugOn)
rtm := api.NewRTM()
go rtm.ManageConnection()
// Go Playground client
gpClient := utils.GoPlaygroundClient{
Host: config.GoPlaygroundHost,
DebugOn: config.DebugOn,
}
// Channel pipeline: unfiltered -> filtered
unfiltered := make(chan *utils.MessageContext)
filtered := make(chan *utils.MessageContext)
go filterRequests(unfiltered, filtered)
go buildResponses(filtered, gpClient)
Loop:
for {
select {
case msg := <-rtm.IncomingEvents:
switch event := msg.Data.(type) {
case *slack.MessageEvent:
mc := utils.NewMessageContext(api, event, config)
go func() { unfiltered <- mc }()
case *slack.RTMError:
log.Printf("Error Receiving event: %s\n", event.Error())
case *slack.InvalidAuthEvent:
log.Printf("Invalid credentials")
break Loop
default:
// Ignore all other types
}
}
}
}