This repository has been archived by the owner on Jan 3, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 12
/
dialogflow.go
68 lines (60 loc) · 2.31 KB
/
dialogflow.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
package dialogflow
import (
"encoding/json"
"errors"
"fmt"
"strings"
)
// Request is the top-level struct holding all the information
// Basically links a response ID with a query result.
type Request struct {
Session string `json:"session,omitempty"`
ResponseID string `json:"responseId,omitempty"`
QueryResult QueryResult `json:"queryResult,omitempty"`
OriginalDetectIntentRequest json.RawMessage `json:"originalDetectIntentRequest,omitempty"`
}
// GetParams simply unmarshals the parameters to the given struct and returns
// an error if it's not possible
func (rw *Request) GetParams(i interface{}) error {
return json.Unmarshal(rw.QueryResult.Parameters, &i)
}
// GetContext allows to search in the output contexts of the query
func (rw *Request) GetContext(ctx string, i interface{}) error {
for _, c := range rw.QueryResult.OutputContexts {
if strings.HasSuffix(c.Name, ctx) {
return json.Unmarshal(c.Parameters, &i)
}
}
return errors.New("context not found")
}
// NewContext is a helper function to create a new named context with params
// name and a lifespan
func (rw *Request) NewContext(name string, lifespan int, params interface{}) (*Context, error) {
var err error
var b []byte
if b, err = json.Marshal(params); err != nil {
return nil, err
}
ctx := &Context{
Name: fmt.Sprintf("%s/contexts/%s", rw.Session, name),
LifespanCount: lifespan,
Parameters: b,
}
return ctx, nil
}
// QueryResult is the dataset sent back by DialogFlow
type QueryResult struct {
QueryText string `json:"queryText,omitempty"`
Action string `json:"action,omitempty"`
LanguageCode string `json:"languageCode,omitempty"`
AllRequiredParamsPresent bool `json:"allRequiredParamsPresent,omitempty"`
IntentDetectionConfidence float64 `json:"intentDetectionConfidence,omitempty"`
Parameters json.RawMessage `json:"parameters,omitempty"`
OutputContexts []*Context `json:"outputContexts,omitempty"`
Intent Intent `json:"intent,omitempty"`
}
// Intent describes the matched intent
type Intent struct {
Name string `json:"name,omitempty"`
DisplayName string `json:"displayName,omitempty"`
}