Categorygithub.com/drpsychick/go-alexa-lambda
modulepackage
0.3.11
Repository: https://github.com/drpsychick/go-alexa-lambda.git
Documentation: pkg.go.dev

# README

Go Report Card Workflow Status Coverage Status license GitHub stars Paypal GitHub Sponsor

go-alexa-lambda

Alexa golang library to generate skill + interaction model as well as serve requests with lambda or as a server. The packages can also be used standalone as a request/response abstraction for Alexa requests.

Purpose

The Alexa skill and interaction model is tightly coupled with the actual intents a lambda function will process. As developing a skill with a golang backend impacts the skill definition in many cases and they share localization scope, this package allows defining and generating the skill and model for deployment and using the same source (with intents, localization) to build the lambda function that responds to requests from Alexa.

Usage

Build skill and interaction model

Run it on go playground: https://play.golang.org/p/VfHW4RcUVwn

package main

import (
	"log"

	alexa "github.com/drpsychick/go-alexa-lambda"
	"github.com/drpsychick/go-alexa-lambda/l10n"
	"github.com/drpsychick/go-alexa-lambda/skill"
	jsoniter "github.com/json-iterator/go"
)

// Configure locale registry.
var enUS = &l10n.Locale{
	Name: "en-US",
	TextSnippets: map[string][]string{
		l10n.KeySkillName:   {"This is my awesome skill."},
		l10n.KeySkillDescription: {"Description"},
		l10n.KeySkillSummary: {"Skill summary"},
		l10n.KeySkillSmallIconURI: {"https://my-url.com/small.png"},
		l10n.KeySkillLargeIconURI: {"https://my-url.com/large.png"},
		l10n.KeySkillTestingInstructions: {"Testing instructions"},
		l10n.KeySkillInvocation: {"awesome skill"},
		// ... for each locale, define the required keys
	},
}

func main() {
	reg := l10n.NewRegistry()
	reg.Register(enUS)

	// Create and configure skill builder.
	s := skill.NewSkillBuilder().
		WithLocaleRegistry(reg).
		WithCategory(skill.CategoryGames).
		WithPrivacyFlag(skill.FlagIsExportCompliant, true).
		WithModel()

	// Configure model.
	s.Model().
		WithDelegationStrategy(skill.DelegationSkillResponse).
		WithIntent(alexa.StopIntent)

	// Build `skill.json`
	sj, err := s.Build()
	if err != nil {
		log.Fatal(err)
	}
	res, _ := jsoniter.MarshalIndent(sj, "", "  ")
	log.Printf("Skill:\n%s", res)

	// Build interaction model: `en-US.json`
	ms, err := s.BuildModels()
	if err != nil {
		log.Fatal(err)
	}
	for l, m := range ms {
		res, _ := jsoniter.MarshalIndent(m, "", "  ")
		log.Printf("Locale %s:\n%s", l, res)
	}
}

Respond to alexa requests with lambda

Run it on go playground: https://play.golang.org/p/fRrzn_kmaBi

package main

import (
	"os"
	"context"
	alexa "github.com/drpsychick/go-alexa-lambda"
	"github.com/drpsychick/go-alexa-lambda/skill"
	log "github.com/hamba/logger/v2"
)

var request = `{
  "version": "1.0",
  "session": {},
  "context": {},
  "request": {
    "type": "IntentRequest",
    "requestId": "amzn1.echo-api.request.1234",
    "timestamp": "2016-10-27T21:06:28Z",
    "locale": "en-US",
    "intent": {
      "name": "AMAZON.HelpIntent"
    }
  }
}
`

func handleHelp(sb *skill.SkillBuilder) alexa.HandlerFunc {
	sb.Model().WithIntent(alexa.HelpIntent)

	return alexa.HandlerFunc(func(b *alexa.ResponseBuilder, r *alexa.RequestEnvelope) {
		b.WithSimpleCard("Help Title", "Text explaining how it works.")
	})
}

func main() {
	sb := skill.NewSkillBuilder()
	mux := alexa.NewServerMux(log.New(os.Stdout, log.ConsoleFormat(), log.Info))
	sb.WithModel()

	mux.HandleIntent(alexa.HelpIntent, handleHelp(sb))
	
	// actually, one would call `alexa.Serve(mux)`
	// but for this demo, we want to pass a request and get a response
	s := &alexa.Server{Handler: mux}
	ctx := context.Background()
	response, err := s.Invoke(ctx, []byte(request))
	if err != nil {
		mux.Logger().Error(err.Error())
	}
	mux.Logger().Info(string(response))
}

Projects using go-alexa-lambda

  • alexa-go-cloudformation-demo : the demo project that lead to developing this library. A fully automated build and deploy of an Alexa skill including lambda function via Cloudformation.

Project template

To give you a head start, check out the template project:

Create your own project based on the template

git clone https://github.com/DrPsychick/go-alexa-lambda-template.git
mv go-alexa-lambda-template alexa-project
cd alexa-project
rm -rf .git

Required variables for your pipeline

ASKClientId= # amzn1.application-oa2-client...
ASKClientSecret= # 6ef4...
ASKAccessToken= # Atza|IwE...
ASKRefreshToken= # 	Atzr|IwE...
ASKVendorId= # M3D....
ASKS3Bucket= # my-bucket
ASKS3Key= # my-skill.zip
ASKSkillId= # amzn1.ask.skill.fe19...
ASK_CONFIG= # cat ~/.ask/cli_config | jq -c | sed -e 's#\(["{}|]\)#\\\1#g'
AWS_DEFAULT_REGION= # eu-central-1
AWS_ACCESS_KEY_ID= # AKD...
AWS_SECRET_ACCESS_KEY= # 3D+...
CF_STACK_NAME= # skill-stack
KEEP_STACK= # if empty, the CF stack will be deleted after deploy (for tests)

References

Links

Credits

initially inspired by: https://github.com/soloworks/go-alexa-models

# Packages

Package l10n provides locale helpers (LocaleRegistry) and predefined standard keys for Alexa skills.
Package skill contains the builders for the skill manifest and interaction models.
Package ssml provides functions to simplify working with SSML speech.

# Functions

CheckForLocaleError returns a ResponseError for the last locale error.
GetLocaleWithFallback falls back to default locale which must be considered carefully.
HandleError handles default and ResponseErrors.
HandleIntent registers the handler for the given intent on the DefaultServeMux.
HandleIntentFunc registers the handler function for the given intent on the DefaultServeMux.
HandleRequestType registers the handler for the given request type on the DefaultServeMux.
HandleRequestTypeFunc registers the handler function for the given request type on the DefaultServeMux.
NewServerMux creates a new server mux.
Serve serves the given handler.

# Constants

AudioPlayerActivityBufferUnderrun Buffer underrun.
AudioPlayerActivityFINISHED Stream was finished playing.
AudioPlayerActivityIDLE Nothing was playing, no enqueued items.
AudioPlayerActivityPAUSED Stream was paused.
AudioPlayerActivityPLAYING Stream was playing.
AudioPlayerActivitySTOPPED Stream was interrupted.
CancelIntent is the Alexa built-in Cancel Intent.
ConfirmationStatusConfirmed is constant `CONFIRMED`.
ConfirmationStatusDenied is constant `DENIED`.
ConfirmationStatusNone is constant `NONE`.
ContextViewportModeAuto defines a AUTO device.
ContextViewportModeHUB defines a HUB device.
ContextViewportModeMobile defines a MOBILE device.
ContextViewportModePC defines a PC device.
ContextViewportModeTV defines a TV device.
ContextViewportShapeRectangle defines a rectangular shape.
ContextViewportShapeRound defines a round shape.
DialogStateCompleted defines a completed dialog.
DialogStateInProgress defines a dialog in progress.
DialogStateStarted defines a started dialog.
Directive types.
Directive types.
Directive types.
Directive types.
HelpIntent is the Alexa built-in Help Intent.
LocaleAmericanEnglish is the locale for American English.
LocaleAustralianEnglish is the locale for Australian English.
LocaleBritishEnglish is the locale for UK English.
LocaleCanadianEnglish is the locale for Canadian English.
LocaleCanadianFrench is the locale for Canadian French.
LocaleFrench is the locale for French (France).
LocaleGerman is the locale for standard dialect German (Germany).
LocaleIndianEnglish is the locale for Indian English.
LocaleItalian is the locale for Italian (Italy).
LocaleJapanese is the locale for Japanese (Japan).
LocaleMexicanSpanish is the locale for Mexican Spanish.
LocaleSpanish is the for Spanish (Spain).
ResolutionStatusException is the status code for an error in processing.
ResolutionStatusMatch is the status code for match.
ResolutionStatusNoMatch is the status code for no match.
ResolutionStatusTimeout is the status code for an error due to timeout.
StopIntent is the Alexa built-in Stop Intent.
TypeCanFulfillIntentRequest defines a can fulfill intent request type.
TypeIntentRequest defines a intent request type.
TypeLaunchRequest defines a launch request type.
TypeSessionEndedRequest defines a session end request type.

# Variables

DefaultServerMux is the default mux.
Error constants.
Error constants.

# Structs

AudioItem represents a response directive audio item.
AuthorityValue is an entry in the list of values.
AuthorityValueValue points to the unique ID and value.
CanFulfillIntent represents a response indicating if an intent can be fulfilled.
CanFulfillSlot represents a slots fulfillment.
Card presents a card response.
Context represents the Alexa skill request context.
ContextApplication is used to verify that the request was intended for your service The ID is the application ID for your skill.
ContextAudioPlayer is available when the device has an audio player.
ContextSystem provides information about the current state of the Alexa service and the interacting device.
ContextSystemPerson describes the person who is making the request to Alexa This is the user recognized by voice, not account from which the request came.
ContextUser a string that represents a unique identifier for the Amazon account for which the skill is enabled.
ContextViewport provides information about the viewport if the device has a screen.
ContextViewportType defines an available viewport of the device.
Directive represents a response directive.
Image represents a card image.
Intent is the Alexa skill intent.
NotFoundError defines a generic not found error.
OutputSpeech represents a speech response.
PerAuthority encapsulates an Authority which is the source of the data provided.
Reprompt represents a reprompt response.
Request represents the information about the request.
RequestEnvelope represents the alexa request envelope.
Resolutions is an Alexa skill resolution.
ResolutionStatus indicates the results of attempting to resolve the user utterance against the defined slot types.
Response wraps the data needed for a skill response.
ResponseBuilder builds a response.
ResponseEnvelope represents the wrapper for a response.
ServeMux is an Alexa request multiplexer.
A Server defines parameters for running an Alexa server.
Session represents the Alexa skill session.
Slot is an Alexa skill slot.
SlotValue defines the value or values captured by the slot.
Stream represents a response directive audio item stream.
TextError returns the error text to Alexa.
TranslationError defines a missing translation error.
ViewportConfiguration contains the viewport configuration of the device in use.
ViewportExperience has info about the device.

# Interfaces

Application defines the interface used of the app.
Handler represents an alexa request handler.
ResponseError defines a response error.

# Type aliases

AudioPlayerActivity defines the activities of an audio player.
ConfirmationStatus represents confirmationStatus in JSON.
ContextViewportMode is the mode for the device.
ContextViewportShape is the shape of the device.
DialogStateType represents JSON request `request.dialogState` see https://developer.amazon.com/docs/custom-skills/delegate-dialog-to-alexa.html.
DirectiveType represents various Directive Types.
HandlerFunc is an adapter allowing a function to be used as a handler.
RequestLocale represents the locale of the request.
RequestType represents JSON request `request.type` see https://developer.amazon.com/docs/custom-skills/request-types-reference.html.
StatusCode represents the status code of a slot resolution.