-
Notifications
You must be signed in to change notification settings - Fork 0
/
alexa.go
69 lines (59 loc) · 1.62 KB
/
alexa.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
package fsmalexa
import (
"bytes"
"encoding/json"
"fmt"
"net/http"
"github.com/go-carrot/fsm"
)
// DistillIntent is a function that is responsible for converting
// an intent into an input string
type DistillIntent func(Intent) string
// GetAlexaWebhook returns the webhook that Alexa expects to communicate with
func GetAlexaWebhook(stateMachine fsm.StateMachine, store fsm.Store, distillIntent DistillIntent) func(http.ResponseWriter, *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
// Get body
buf := new(bytes.Buffer)
buf.ReadFrom(r.Body)
body := buf.String()
// Parse body into struct
cb := &RequestBody{}
err := json.Unmarshal([]byte(body), cb)
if err != nil {
fmt.Println(err)
w.WriteHeader(http.StatusInternalServerError)
return
}
// Get traverser
newTraverser := false
traverser, err := store.FetchTraverser(cb.Session.User.UserID)
if err != nil {
traverser, _ = store.CreateTraverser(cb.Session.User.UserID)
traverser.SetCurrentState("start")
newTraverser = true
}
// Create emitter
emitter := &AlexaEmitter{
ResponseWriter: w,
}
// Get current state
currentState := stateMachine[traverser.CurrentState()](emitter, traverser)
if newTraverser {
currentState.EntryAction()
}
// Transition
distilledValue := distillIntent(cb.Request.Intent)
newState := currentState.Transition(distilledValue)
err = newState.EntryAction()
if err == nil {
traverser.SetCurrentState(newState.Slug)
}
// Write body
err = emitter.Flush()
if err != nil {
fmt.Println(err)
w.WriteHeader(http.StatusInternalServerError)
return
}
}
}