/
main.go
452 lines (360 loc) · 10.3 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
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
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
package main
import (
"fmt"
"net/http"
"log"
"html"
"io/ioutil"
"github.com/nlopes/slack"
"time"
"strings"
"bytes"
"strconv"
"encoding/json"
"github.com/melvinmt/firebase"
)
func main(){
api := slack.New("INSERT TOKEN")
api.SetDebug(false)
http.HandleFunc("/webhook", func(w http.ResponseWriter, r *http.Request) {
log.Println("hit webhook")
requestBody, err := ioutil.ReadAll(r.Body);
if err != nil {
log.Println("err ",err)
}
log.Print("request body ",string(requestBody))
log.Print("request url ",r.URL)
var results FormResults
err = json.Unmarshal(requestBody, &results)
if (err != nil) {
log.Println("COULD NOT UNMARSHALL RESULTS ",err)
}
log.Println("UNMARSHALLED RESULSTs ", results)
userId := r.URL.Query().Get("id")
timestamp := r.URL.Query().Get("timestamp")
chanId := r.URL.Query().Get("chanId")
log.Println("timestamp ",timestamp, " chanId ",chanId)
user, err := api.GetUserInfo(userId)
if (err != nil) {
fmt.Println("Could not find person with id ",userId )
}
storeVotedPersonInFirebase(user)
storeResultInFirebase(results)
dmPerson(user, "thank you for voting!! See the results at http://3d8d52d9.ngrok.io/", api) //ADD link to results
// itemRef := slack.NewRefToMessage(chanId, timestamp)
// err = api.AddReaction("+1", itemRef)
// if (err != nil) {
// fmt.Println("Could not post reaction, ", err)
// }
msg := fmt.Sprintf("%v just voted! See the results at http://3d8d52d9.ngrok.io/",user.Name)
api.PostMessage("C085QFNM7", msg, slack.PostMessageParameters {
AsUser: true,
})
//store results in db DONE
//save user image to indicate they've voted DONE
//send a dm to thank the person and show results page DONE
//add reaction to message DONE
fmt.Fprintf(w, "Hello, %q", html.EscapeString(r.URL.Path))
})
go setupRTM(api)
log.Println("Listening on 8080...")
log.Fatal(http.ListenAndServe(":8080", nil))
}
func setupRTM (api *slack.Slack) {
chSender := make(chan slack.OutgoingMessage)
chReceiver := make(chan slack.SlackEvent)
wsAPI, err := api.StartRTM("", "http://example.com")
if err != nil {
fmt.Errorf("%s\n", err)
}
go wsAPI.HandleIncomingEvents(chReceiver)
go wsAPI.Keepalive(20 * time.Second)
go func(wsAPI *slack.SlackWS, chSender chan slack.OutgoingMessage) {
for {
select {
case msg := <-chSender:
wsAPI.SendMessage(&msg)
}
}
}(wsAPI, chSender)
for {
select {
case msg := <-chReceiver:
fmt.Print("Event Received: ")
switch msg.Data.(type) {
case slack.HelloEvent:
// Ignore hello
case *slack.MessageEvent:
a := msg.Data.(*slack.MessageEvent)
fmt.Printf("Message: %v\n", a)
fmt.Printf("ChanID:",a.ChannelId)
if (strings.Contains(a.Text, "U085QG8D7")) {
createFormForEverybody( a, api )
}
case *slack.PresenceChangeEvent:
a := msg.Data.(*slack.PresenceChangeEvent)
fmt.Printf("Presence Change: %v\n", a)
case slack.LatencyReport:
a := msg.Data.(slack.LatencyReport)
fmt.Printf("Current latency: %v\n", a.Value)
case *slack.SlackWSError:
error := msg.Data.(*slack.SlackWSError)
fmt.Printf("Error: %d - %s\n", error.Code, error.Msg)
default:
fmt.Printf("Unexpected: %v\n", msg.Data)
}
}
}
}
func dmPerson (user *slack.User, message string, api *slack.Slack) {
if (user.Name == "typebot") {
return
}
_,_,chanId, err := api.OpenIMChannel(user.Id)
if (err != nil) {
fmt.Println("IM err ",err)
}
api.PostMessage(chanId, message, slack.PostMessageParameters {
AsUser: true,
})
}
func dmAll(message string, api *slack.Slack) {
users, err := api.GetUsers()
if (err != nil) {
fmt.Println("Channel err ",err)
}
for _, user := range users {
if (user.Name == "typebot") {
continue
}
_,_,chanId, err := api.OpenIMChannel(user.Id)
if (err != nil) {
fmt.Println("IM err ",err)
}
api.PostMessage(chanId, message, slack.PostMessageParameters {
AsUser: true,
})
}
}
func createFormForEverybody(formMessage *slack.MessageEvent, api *slack.Slack) {
users, err := api.GetUsers()
if (err != nil) {
fmt.Println("Channel err ",err)
}
for _, user := range users {
//create user form DONE
//send dm to fill out form DONE
formResp := createFormForUser(formMessage, user.Id)
if (user.Name == "typebot" || user.Id == "U085QG8D7") {
continue
}
_, _, chanId, err := api.OpenIMChannel(user.Id)
if (err != nil) {
fmt.Println("IM err ",err)
}
fmt.Println("formResp ",formResp)
formDM := fmt.Sprintf("A form has been created, go fill it out! %v", formResp.Links[1].Href)
api.PostMessage(chanId, formDM, slack.PostMessageParameters {
AsUser: true,
})
}
}
func createFormForUser(message *slack.MessageEvent, userId string) FormSubmissionResponse {
msgComponents := strings.Split(message.Text, "|")
log.Println("msgComponents ",msgComponents)
if ( len(msgComponents) < 2 ) {
log.Println("not enough data to create form")
return FormSubmissionResponse{}
}
question := strings.Split(msgComponents[0], ":")[1]
rawChoices := msgComponents[1:]
choices := []Choice{}
for _, choice := range rawChoices {
choiceComponents := strings.Split(choice, ",")
parseString := strings.Trim(choiceComponents[1], " ")
imgId64, err := strconv.ParseInt(parseString, 10, 32)
if (err != nil) {
fmt.Println("err parsing ",err)
}
fmt.Println("imgId64",imgId64)
imgId := int(imgId64)
fmt.Println("imgId",imgId)
choices = append(choices, *NewChoice(imgId, choiceComponents[0]))
}
url := "https://api.typeform.io/v0.3/forms"
webhook := fmt.Sprintf("https://4c7e576f.ngrok.io/webhook?id=%v×tamp=%v&chanId=%v",userId, message.Timestamp, message.ChannelId)
formSubmission := NewFormSubmission(question, choices, webhook)
// sample message => "Would you rather | Fight a horse sized duck?, 2542 | Fight a thousand duck sized horses?, 2543"
rawSubmission, _ := json.Marshal(formSubmission)
buf := bytes.NewBuffer(rawSubmission)
req, err := http.NewRequest("POST", url, buf)
if (err != nil) {
fmt.Println("Could not build new request ",err)
}
req.Header.Add("x-api-token", "INSERT TOKEN")
res, err := http.DefaultClient.Do(req)
if (err != nil) {
fmt.Println("Could not execute request ",err)
}
defer res.Body.Close()
body, _ := ioutil.ReadAll(res.Body)
var resp FormSubmissionResponse
err = json.Unmarshal(body, &resp)
if (err != nil) {
fmt.Println("Could not unmarshall form repsonse ",err)
}
return resp
}
func NewFormSubmission (question string, choices []Choice, webhook string) *FormSubmission {
field := Field{
Choices : choices,
Question : question,
Required : true,
Type : "picture_choice",
}
return &FormSubmission{
Fields : []Field{field},
WebhookSubmitURL : webhook,
Title : "Typeform hackathon question",
}
}
type FormSubmission struct {
Fields []Field `json:"fields"`
Title string `json:"title"`
WebhookSubmitURL string `json:"webhook_submit_url"`
}
type Field struct {
Choices []Choice `json:"choices"`
Description string `json:"description"`
Question string `json:"question"`
Required bool `json:"required"`
Type string `json:"type"`
}
type Choice struct {
ImageID int `json:"image_id"`
Label string `json:"label"`
}
func NewChoice(imageId int, label string) *Choice {
return &Choice{
ImageID: imageId,
Label: label,
}
}
type FormResults struct {
Answers []struct {
Data struct {
Type string `json:"type"`
Value struct {
Label string `json:"label"`
Other interface{} `json:"other"`
} `json:"value"`
} `json:"data"`
FieldID float64 `json:"field_id"`
} `json:"answers"`
ID string `json:"id"`
Token string `json:"token"`
}
type FormSubmissionResponse struct {
Fields []struct {
AllowMultipleSelections bool `json:"allow_multiple_selections"`
Choices []struct {
Filename string `json:"filename"`
Height int `json:"height"`
ImageID int `json:"image_id"`
Label string `json:"label"`
Width int `json:"width"`
} `json:"choices"`
Description string `json:"description"`
ID int `json:"id"`
Labels bool `json:"labels"`
Question string `json:"question"`
Required bool `json:"required"`
Type string `json:"type"`
} `json:"fields"`
ID string `json:"id"`
Links []struct {
Href string `json:"href"`
Rel string `json:"rel"`
} `json:"links"`
Title string `json:"title"`
WebhookSubmitURL string `json:"webhook_submit_url"`
}
func storeVotedPersonInFirebase(user *slack.User) {
var err error
url := "https://typeformhackathon.firebaseio.com/votedUsers"
// Can also be your Firebase secret:
authToken := "INSERT TOKEN HERE"
// Auth is optional:
ref := firebase.NewReference(url).Auth(authToken)
// Write the value to Firebase.
if err = ref.Push(user); err != nil {
panic(err)
}
}
func storeResultInFirebase(results FormResults) {
var err error
url := "https://typeformhackathon.firebaseio.com/answers"
// Can also be your Firebase secret:
authToken := "INSERT TOKEN HERE"
// Auth is optional:
ref := firebase.NewReference(url).Auth(authToken)
// Write the value to Firebase.
if err = ref.Push(results); err != nil {
panic(err)
}
log.Println("WROTE TO FIREBASE")
// // Now, we're going to retrieve the person.
// personUrl := "https://SampleChat.firebaseIO-demo.com/users/fred"
//
// personRef := firebase.NewReference(personUrl).Export(false)
//
// fred := Person{}
//
// if err = personRef.Value(fred); err != nil {
// panic(err)
// }
//
// fmt.Println(fred.Name.First, fred.Name.Last) // prints: Fred Swanson
}
/*
{
"title":"Typeform IO hackathon",
"webhook_submit_url":"http://22c95451.ngrok.io/webhook",
"fields":[
{
"type":"picture_choice",
"question":"What would you rather fight?",
"description":"Life or death decision",
"required":true,
"choices":[
{
"image_id":2542,
"label":"A horse sized duck"
},
{FormSubmission
"image_id":2543,
"label":"A thousand duck sized horses"
}
]
}
]
}
*/
/*
{
"answers":[
{
"data":{
"type":"choice",
"value":{
"label":" Fight a thousand duck sized horses?",
"other":null
}
},
"field_id":1.272649e+06
}
],
"id":"S65RosIui4nvig",
"token":"BLAHBLAH"
}
*/