okgohook

package module
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Feb 21, 2022 License: MIT Imports: 13 Imported by: 0

README

ignaci0/okgohook

This module, composed by two packages provides the means to implement fulfillment service webhooks so Actions On Google can send to a running server.

It's important to remark this module does not implement DialogFlow fulfillments but fulfillment services for the new conversational actions.

This module's features include:

  • Implementation of http.Handler interface so that it is compatible with http.ServeMux (and other modules such as gorilla/mux)
  • It provides data types for the fulfillment requests (complete) and response (partial) ; missing ones can be introduced later by comunity or myself upon need
  • It implements HealthCheck system intent route
  • It supports request verification by validating JWT received and the intended audience
  • Additional matching rules out of the box: locale and handler
  • Matcher interface to introduce custom request matchers

To get started building your own actions this is the place to go.

Since actions can be run in alfa channel, this is quite convenient to run home server's automated tasks.


Install

Assuming go toolchain is available:

go get github.com/ignaci0/okgohook

Examples

Hello World

Just because:

webhookRouter := okgohook.NewRouter()
webhookRouter.HandleIntent("hello", func (req *aog.FulfillmentRequest) *aog.FulfillmentResponse {
	return &aog.FulfillmentResponse {
		Prompt: &aog.Prompt {
			FirstSimple: &aog.Simple { Speech: "Hello World!" },
		},
	}
}) 

//Let's use gorilla/mux for this sample:
router := mux.NewRouter()
router.Handle("/webhook", webhookRouter)
//It plays well with other handlers, e.g.:
//router.PathPrefix("/").Handler...

srv := &http.Server {
	Handler: router,
	Address: ":8080",
	WriteTimeout: 2 * time.Second,
	ReadTimeout: 2 * time.Second,
}

log.Fatal(srv.ListenAndServe())
Basic Echo

This sample fulfillment function talks back the user request:

webhookRouter := okgohook.NewRouter()
webhookRouter.HandleIntent("hello", func (req *aog.FulfillmentRequest) *aog.FulfillmentResponse {
	return &aog.FulfillmentResponse {
		Prompt: &aog.Prompt {
			FirstSimple: &aog.Simple { Speech: req.Intent.Query },
		},
	}
}) 
With additional matches
webhookRouter := okgohook.NewRouter()

webhookRouter.HandleIntent("hello", func (req *aog.FulfillmentRequest) *aog.FulfillmentResponse { }).WithHandler("world").WithLocaleLike("EN")
webhookRouter.HandleIntent("hello", func (req *aog.FulfillmentRequest) *aog.FulfillmentResponse { }).WithHandler("world").WithLocaleLike("ES")
With token verification and authorization

Currently it is not possible to verify the token without audience verification.

webhookRouter := okgohook.NewRouter().Authorize("my-app")

When the newly created router is provided with an audience, a goroutine is launched to retrieve and keep up to date the signing token certificates. This means the server shall require access to the internet to retrieve them.

TO-DOs/Roadmap

  • Remove unnecessary logging and add a logger facility/middlewares
  • Implement missing response types
  • Change the certificates verifications to a newer keys url
  • Add proxy support for certificates retrieval
  • Find a way to get rid off the aog package by autogenerating code for from the gRPC specification

Documentation

Overview

Provides the data types for the routes matchinng

This package primaraly's purpose is to provide a router for implementing a webhook and conviniently handle the intent's fulfillment requests towards the webhook.

The Router implements' net/http Handler interface to serve Google Actions webhook requests that are provided in the routes. Creating a webhook is as simple as:

router := okgohook.NewRouter()
router.HandleIntent("HelloWorld", func(aog.FulfillmentRequest) *aog.Fulfillmentresponse { ... })
http.Handle(router) // Other routers such as gorilla/mux can be used as well
log.Fatal(http.ListenAndServe(":6060", nil))

The default router shall also respond the Google Health checks sent for analytics

Index

Constants

View Source
const ACTIONS_INTENT_HEALTH_CHECK = "actions.intent.HEALTH_CHECK"

Variables

This section is empty.

Functions

This section is empty.

Types

type FulfillmentFunction

type FulfillmentFunction func(fr *aog.FulfillmentRequest) *aog.FulfillmentResponse

Function type for processing Google actions' fulfillment requests These functions must return a pointer to the response so that the Router can Encode it and send the proper response back.

func MyHandler(fr *aog.FulfillmentRequest) *aog.FulfillmentResponse {
	return &aog.FulfillmentResponse{
	Prompt: &aog.Prompt{
		FirstSimple: &aog.Simple{
			Speech: "Hello World",
		},
	},
}

type Matcher

type Matcher interface {
	Matches(*aog.FulfillmentRequest) bool
}

A okgohook.Matcher can be used as a custom match for routes to match a given request. If the request is not to be processed by the route Matches shall return false, otherwise (yes or condition ignored) true.

type Route

type Route struct {
	// contains filtered or unexported fields
}

Route stores the action for an intent along with additional conditions such as conditions on handlers, locale or custom provided.

The when the route is matched (the intent is matched and all the matchers return true, then the funcion FulfillmentFunction is executed).

func (*Route) Match

func (this *Route) Match(m *Matcher) *Route

Takes a custom Matcher for testing the request

func (*Route) MatchCustomFunc

func (this *Route) MatchCustomFunc(f func(*aog.FulfillmentRequest) bool) *Route

Adds a custom match function for the given intent to filter undesired requests for the given IntentHandler function

func (*Route) WithHandler

func (this *Route) WithHandler(handler string) *Route

Adds a condition to match the exact handler in the aog.FulfillmentRequest

Example usage:

myRouter.HandleIntent("hello_world", helloWolrdIntent).WithHandler("new-joiner")

func (*Route) WithHandlerLike

func (this *Route) WithHandlerLike(h string) *Route

Adds a condition to match the provided regular expression in the aog.FulfillmentRequest

Example usage:

myRouter.HandleIntent("hello_world", helloWolrdIntent).WithHandler(".*-joiner$")

func (*Route) WithLocaleLike

func (this *Route) WithLocaleLike(l string) *Route

Matches the locale of the fulfillment request to the provided regular expression

Example usage:

myRouter.HandleIntent("hello_world", helloWolrdIntent).WithLocaleLike("^EN-.*")

type Router

type Router struct {
	// contains filtered or unexported fields
}

Router implements net/http's Handler interface to serve POST requests from Google Actions by serving the configured routes.

func NewRouter

func NewRouter() *Router

NewRouter allocates and initializes a pointer to a Router struct adding also the default intent handlers.

var router *okgohook.Router
router = okgohook.NewRouter()

func (*Router) Authorize

func (this *Router) Authorize(aud string, proxy ...string) *Router

Authorizes requests against the given audience. It also enables token verification and it launches a certificate retrieval goroutine. Only one proxy is accepted and if provided it shall be used to retrieve the certificates through it

func (*Router) HandleIntent

func (this *Router) HandleIntent(intent string, fn FulfillmentFunction) *Route

HandleIntent creates a Route within the Router that shall be handled by fn.

Additional criterias can be added to the Route by using provided or custom Matchers.

Example:

myrouter.HandleIntent("hello_workld", func(fr *aog.FulfillmentRequest) *aog.FulfillmentResponse {
	return &aog.FulfillmentResponse {
		//...your hello world prompt goes here
	}
}

func (*Router) HealthCheck

func (this *Router) HealthCheck(fn FulfillmentFunction)

Function to replace the default provided health check intent.

It is likely this will never be required

func (*Router) Proxy added in v0.2.0

func (this *Router) Proxy(url string)

func (*Router) ServeHTTP

func (this *Router) ServeHTTP(w http.ResponseWriter, req *http.Request)

Directories

Path Synopsis
The types provided in this package are for decoding and encoding the JSON objects set by the Actions on Google for a webhook The data types provided in this package are documented here: (https://developers.google.com/assistant/conversational/reference/rest/v1/TopLevel/fulfill As of now, this package does not implement all the types and further work is required.
The types provided in this package are for decoding and encoding the JSON objects set by the Actions on Google for a webhook The data types provided in this package are documented here: (https://developers.google.com/assistant/conversational/reference/rest/v1/TopLevel/fulfill As of now, this package does not implement all the types and further work is required.

Jump to

Keyboard shortcuts

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