dialogflow

package module
v1.1.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 25, 2018 License: MIT Imports: 5 Imported by: 5

README

Dialogflow Go Webhook

Go Version Go Version Go Report Card Build Status codecov License Godoc

Simple library to create compatible DialogFlow v2 webhooks using Go.

This package is only intended to create webhooks, it doesn't implement the whole DialogFlow API.

⛔ Deprecation Notice

This project is no longer useful since the release of the Go SDK for Dialogflow's v2 API. See this article for a tutorial on how to use the protobuf definition to handle webhook.

Table of Content

Introduction

Goal of this package

This package aims to implement a complete way to receive a DialogFlow payload, parse it, and retrieve data stored in the parameters and contexts by providing your own data structures.

It also allows you to format your response properly, the way DialogFlow expects it, including all the message types and platforms. (Such as cards, carousels, quick replies, etc…)

Disclaimer

As DialogFlow's v2 API is still in Beta, there may be breaking changes. If something breaks, please file an issue.

Installation

Using dep

If you're using dep which is the recommended way to vendor your dependencies in your project, simply run this command :

dep ensure -add github.com/leboncoin/dialogflow-go-webhook

Using go get

If your project isn't using dep yet, you can use go get to install this package :

go get github.com/leboncoin/dialogflow-go-webhook

Usage

Import the package github.com/leboncoin/dialogflow-go-webhook and use it with the dialogflow package name. To make your code cleaner, import it as df. All the following examples and usages use the df notation.

Handling incoming request

In this section we'll use the gin router as it has some nice helper functions that will keep the code concise. For an example using the standard http router, see this example.

When DialogFlow sends a request to your webhook, you can unmarshal the incoming data to a df.Request. This, however, will not unmarshal the contexts and the parameters because those are completely dependent on your data models.

package main

import (
	"net/http"

	"github.com/gin-gonic/gin"
	df "github.com/leboncoin/dialogflow-go-webhook"
)

type params struct {
	City   string `json:"city"`
	Gender string `json:"gender"`
	Age    int    `json:"age"`
}

func webhook(c *gin.Context) {
	var err error
	var dfr *df.Request

	if err = c.BindJSON(&dfr); err != nil {
		c.AbortWithStatus(http.StatusBadRequest)
		return
	}
}

func main() {
	r := gin.Default()
	r.POST("/webhook", webhook)
	if err := r.Run("127.0.0.1:8001"); err != nil {
		panic(err)
	}
}

Retrieving params and contexts

type params struct {
	City   string `json:"city"`
	Gender string `json:"gender"`
	Age    int    `json:"age"`
}

func webhook(c *gin.Context) {
	var err error
	var dfr *df.Request
	var p params

	if err = c.BindJSON(&dfr); err != nil {
		c.AbortWithStatus(http.StatusBadRequest)
		return
	}

	// Retrieve the params of the request
	if err = dfr.GetParams(&p); err != nil {
		c.AbortWithStatus(http.StatusBadRequest)
		return
	}
}

In this example we're getting the DialogFlow request and unmarshalling the params to a defined struct. This is why json.RawMessage is used in both the Request.QueryResult.Parameters and in the Request.QueryResult.Contexts.

This also allows you to filter and route according to the action and intent DialogFlow detected, which means that depending on which action you detected, you can unmarshal the parameters and contexts to a completely different data structure.

The same thing can be done for contexts :

type params struct {
	City   string `json:"city"`
	Gender string `json:"gender"`
	Age    int    `json:"age"`
}

func webhook(c *gin.Context) {
	var err error
	var dfr *df.Request
	var p params

	if err = c.BindJSON(&dfr); err != nil {
		c.AbortWithStatus(http.StatusBadRequest)
		return
	}

	if err = dfr.GetContext("my-awesome-context", &p); err != nil {
		c.AbortWithStatus(http.StatusBadRequest)
		return
	}
}

Responding with a fulfillment

DialogFlow expects you to respond with what is called a fulfillment.

This package supports every rich response type.

func webhook(c *gin.Context) {
	var err error
	var dfr *df.Request
	var p params

	if err = c.BindJSON(&dfr); err != nil {
		c.AbortWithStatus(http.StatusBadRequest)
		return
	}

	// Send back a fulfillment
	dff := &df.Fulfillment{
		FulfillmentMessages: df.Messages{
			df.ForGoogle(df.SingleSimpleResponse("hello", "hello")),
			{RichMessage: df.Text{Text: []string{"hello"}}},
		},
	}
	c.JSON(http.StatusOK, dff)
}

Examples

Documentation

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type BasicCard

type BasicCard struct {
	Title         string       `json:"title,omitempty"`         // Optional. The title of the card.
	Subtitle      string       `json:"subtitle,omitempty"`      // Optional. The subtitle of the card.
	FormattedText string       `json:"formattedText,omitempty"` // Required, unless image is present. The body text of the card.
	Image         *Image       `json:"image,omitempty"`         // Optional. The image for the card.
	Buttons       []CardButton `json:"buttons,omitempty"`       // Optional. The collection of card buttons.
}

BasicCard is a simple card. Simply adds an extra Image field

func (BasicCard) GetKey

func (bc BasicCard) GetKey() string

GetKey implements the RichMessage interface and returns the JSON key associated with the BasicCard type

type Button

type Button struct {
	Text     string `json:"text,omitempty"`     // Optional. The text to show on the button.
	PostBack string `json:"postback,omitempty"` // Optional. The text to send back to the Dialogflow API or a URI to open.
}

Button contains information about a button

type Card

type Card struct {
	Title    string   `json:"title,omitempty"`    // Optional. The title of the card.
	Subtitle string   `json:"subtitle,omitempty"` // Optional. The subtitle of the card.
	Buttons  []Button `json:"buttons,omitempty"`  // Optional. The collection of card buttons.
	Image
}

Card is a simple card. Different type than the BasicCard, the buttons change. This card has buttons with postback field, whereas BasicCard has cards with OpenURI action

func (Card) GetKey

func (c Card) GetKey() string

GetKey implements the RichMessage interface and returns the JSON key associated with the Card type

type CardButton

type CardButton struct {
	Title         string         `json:"title,omitempty"`         // Optional. The text to show on the button.
	OpenURIAction *OpenURIAction `json:"openUriAction,omitempty"` // Required. Action to take when a user taps on the button.
}

CardButton is a he button object that appears at the bottom of a card

type CarouselSelect

type CarouselSelect struct {
	Items []Item `json:"items,omitempty"` // Required. Carousel items.
}

CarouselSelect shows a carousel to the user

func (CarouselSelect) GetKey

func (c CarouselSelect) GetKey() string

GetKey implements the RichMessage interface and returns the JSON key associated with the CarouselSelect type

type Context

type Context struct {
	Name          string          `json:"name,omitempty"`
	LifespanCount int             `json:"lifespanCount,omitempty"`
	Parameters    json.RawMessage `json:"parameters,omitempty"`
}

Context is a context contained in a query

type Contexts

type Contexts []*Context

Contexts is a slice of pointer to Context

type FollowupEventInput added in v1.1.0

type FollowupEventInput struct {
	Name         string      `json:"name"`
	LanguageCode string      `json:"languageCode,omitempty"`
	Parameters   interface{} `json:"parameters,omitempty"`
}

FollowupEventInput Optional. Makes the platform immediately invoke another sessions.detectIntent call internally with the specified event as input. https://dialogflow.com/docs/reference/api-v2/rest/v2beta1/projects.agent.sessions/detectIntent#EventInput

type Fulfillment

type Fulfillment struct {
	FulfillmentText     string             `json:"fulfillmentText,omitempty"`
	FulfillmentMessages Messages           `json:"fulfillmentMessages,omitempty"`
	Source              string             `json:"source,omitempty"`
	Payload             interface{}        `json:"payload,omitempty"`
	OutputContexts      Contexts           `json:"outputContexts,omitempty"`
	FollowupEventInput  FollowupEventInput `json:"followupEventInput,omitempty"`
}

Fulfillment is the response sent back to dialogflow in case of a successful webhook call

type Image

type Image struct {
	ImageURI string `json:"imageUri,omitempty"` // Optional. The public URI to an image file.
}

Image is a simple type of message sent back to dialogflow

func (Image) GetKey

func (i Image) GetKey() string

GetKey implements the RichMessage interface and returns the JSON key associated with the Image type

type Intent

type Intent struct {
	Name        string `json:"name,omitempty"`
	DisplayName string `json:"displayName,omitempty"`
}

Intent describes the matched intent

type Item

type Item struct {
	Info        SelectItemInfo `json:"info,omitempty"`        // Required. Additional information about this option
	Title       string         `json:"title,omitempty"`       // Required. The title of the list item
	Description string         `json:"description,omitempty"` // Optional. The main text describing the item
	Image       *Image         `json:"image,omitempty"`       // Optional. The image to display.
}

Item is a single item present in a list

type LinkOutSuggestion

type LinkOutSuggestion struct {
	DestinationName string `json:"suggestionName,omitempty"` // Required. The name of the app or site this chip is linking to.
	URI             string `json:"uri,omitempty"`            // Required. The URI of the app or site to open when the user taps the suggestion chip.
}

LinkOutSuggestion can be used to suggest the user to click on a link that will get him out of the app

func (LinkOutSuggestion) GetKey

func (l LinkOutSuggestion) GetKey() string

GetKey implements the RichMessage interface and returns the JSON key associated with the LinkOutSuggestion type

type ListSelect

type ListSelect struct {
	Title string `json:"title,omitempty"` // Required. The overall title of the list.
	Items []Item `json:"items,omitempty"` // Required. List items.
}

ListSelect can be used to show a list to the user

func (ListSelect) GetKey

func (l ListSelect) GetKey() string

GetKey implements the RichMessage interface and returns the JSON key associated with the ListSelect type

type Location

type Location struct {
	Simple               string
	AdminArea            string          `json:"admin-area,omitempty"`
	AdminAreaOriginal    string          `json:"admin-area.original,omitempty"`
	AdminAreaObject      json.RawMessage `json:"admin-area.object,omitempty"`
	SubAdminArea         string          `json:"subadmin-area,omitempty"`
	SubAdminAreaOriginal string          `json:"subadmin-area.original,omitempty"`
}

Location is a location object sent back by DialogFlow

func (*Location) UnmarshalJSON

func (l *Location) UnmarshalJSON(b []byte) error

UnmarshalJSON implements the Unmarshaler interface for JSON parsing This function will try to unmarshal the incoming data to either a full Location object, or a simple string.

type Message

type Message struct {
	Platform
	RichMessage RichMessage
}

Message is a struct holding a platform and a RichMessage. Used in the FulfillmentMessages of the response sent back to dialogflow

func ForGoogle

func ForGoogle(r RichMessage) Message

ForGoogle takes a rich message wraps it in a message with the appropriate platform set

Example
output := "Hello World !"
fulfillment := Fulfillment{
	FulfillmentMessages: Messages{
		ForGoogle(SingleSimpleResponse(output, output)),
	},
}
fmt.Println(fulfillment)
Output:

func (*Message) MarshalJSON

func (m *Message) MarshalJSON() ([]byte, error)

MarshalJSON implements the Marshaller interface for the JSON type. Custom marshalling is necessary since there can only be one rich message per Message and the key associated to each type is dynamic

type Messages

type Messages []Message

Messages is a simple slice of Message

type OpenURIAction

type OpenURIAction struct {
	URI string `json:"uri,omitempty"` // Required. The HTTP or HTTPS scheme URI.
}

OpenURIAction simply defines the URI associated with a button

type PayloadWrapper

type PayloadWrapper struct {
	Payload interface{}
}

PayloadWrapper acts as a wrapper for the payload type

func (PayloadWrapper) GetKey

func (p PayloadWrapper) GetKey() string

GetKey implements the RichMessage interface and returns the JSON key associated to the Payload type

func (PayloadWrapper) MarshalJSON

func (p PayloadWrapper) MarshalJSON() ([]byte, error)

MarshalJSON implements the Marshaller interface and will return the marshalled payload, ignoring the initial level

type Platform

type Platform string

Platform is a simple type intended to be used with responses

const (
	Unspecified     Platform = "PLATFORM_UNSPECIFIED"
	Facebook        Platform = "FACEBOOK"
	Slack           Platform = "SLACK"
	Telegram        Platform = "TELEGRAM"
	Kik             Platform = "KIK"
	Skype           Platform = "SKYPE"
	Line            Platform = "LINE"
	Viber           Platform = "VIBER"
	ActionsOnGoogle Platform = "ACTIONS_ON_GOOGLE"
)

Platform constants, used in the webhook responses

type QueryResult

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"`
}

QueryResult is the dataset sent back by DialogFlow

type QuickReplies

type QuickReplies struct {
	Title   string   `json:"title,omitempty"`        // Optional. The title of the collection of quick replies.
	Replies []string `json:"quickReplies,omitempty"` // Optional. The collection of quick replies.
}

QuickReplies is a structured response sent back to dialogflow

func (QuickReplies) GetKey

func (qr QuickReplies) GetKey() string

GetKey implements the RichMessage interface and returns the JSON key associated with the QuickReplies type

type Request

type Request struct {
	Session                     string          `json:"session,omitempty"`
	ResponseID                  string          `json:"responseId,omitempty"`
	QueryResult                 QueryResult     `json:"queryResult,omitempty"`
	OriginalDetectIntentRequest json.RawMessage `json:"originalDetectIntentRequest,omitempty"`
}

Request is the top-level struct holding all the information Basically links a response ID with a query result.

func (*Request) GetContext

func (rw *Request) GetContext(ctx string, i interface{}) error

GetContext allows to search in the output contexts of the query

func (*Request) GetParams

func (rw *Request) GetParams(i interface{}) error

GetParams simply unmarshals the parameters to the given struct and returns an error if it's not possible

func (*Request) NewContext

func (rw *Request) NewContext(name string, lifespan int, params interface{}) (*Context, error)

NewContext is a helper function to create a new named context with params name and a lifespan

type RichMessage

type RichMessage interface {
	GetKey() string
}

RichMessage is an interface used in the Message type. It is used to send back payloads to dialogflow

type SelectItemInfo

type SelectItemInfo struct {
	Key      string   `json:"key,omitempty"`      //  Required. A unique key that will be sent back to the agent if this response is given.
	Synonyms []string `json:"synonyms,omitempty"` //  Optional. A list of synonyms that can also be used to trigger this item in dialog.
}

SelectItemInfo is a struct holding data about a specific item

type SimpleResponse

type SimpleResponse struct {
	TextToSpeech string `json:"textToSpeech,omitempty"` // One of textToSpeech or ssml must be provided. The plain text of the speech output. Mutually exclusive with ssml.
	DisplayText  string `json:"displayText,omitempty"`  // Optional. The text to display.
	SSML         string `json:"ssml,omitempty"`         // One of textToSpeech or ssml must be provided. Structured spoken response to the user in the SSML format. Mutually exclusive with textToSpeech.
}

SimpleResponse is a simple response sent back to dialogflow. Composed of two types, TextToSpeech will be converted to speech and DisplayText will be displayed if the surface allows to display stuff

type SimpleResponsesWrapper

type SimpleResponsesWrapper struct {
	SimpleResponses []SimpleResponse `json:"simpleResponses,omitempty"` // Required. The list of simple responses.
}

SimpleResponsesWrapper wraps SimpleResponses

func SingleSimpleResponse

func SingleSimpleResponse(display, speech string) SimpleResponsesWrapper

SingleSimpleResponse is a wrapper to create one simple response to display and play to the user

func (SimpleResponsesWrapper) GetKey

func (s SimpleResponsesWrapper) GetKey() string

GetKey implements the RichMessage interface and returns the JSON key associated with the SimpleResponsesWrapper type

type Suggestion

type Suggestion struct {
	Title string `json:"title,omitempty"` // Required. The text shown the in the suggestion chip.
}

Suggestion is a simple suggestion

type Suggestions

type Suggestions struct {
	Suggestions []Suggestion `json:"suggestions,omitempty"` // Required. The list of suggested replies.
}

Suggestions is a rich message that suggests the user quick replies

func (Suggestions) GetKey

func (s Suggestions) GetKey() string

GetKey implements the RichMessage interface and returns the JSON key associated to the Suggestions type

type Text

type Text struct {
	Text []string `json:"text,omitempty"` // Optional. The collection of the agent's responses.
}

Text is a simple wrapper around a list of string

func (Text) GetKey

func (t Text) GetKey() string

GetKey implements the RichMessage interface and returns the JSON key associated with the Text type

Directories

Path Synopsis
examples
gin

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL