Code Monkey home page Code Monkey logo

go-alexa-lambda's Introduction

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

go-alexa-lambda's People

Contributors

drpsychick avatar renovate[bot] avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

go-alexa-lambda's Issues

TODO: ResponseBuilder.Build

empty response with directive(s), like Dialog:Delegate

  • research "Dialog:Delegate"
  • implement a way to use an empty response and delegate the dialog to Alexa

Dependency Dashboard

This issue lists Renovate updates and detected dependencies. Read the Dependency Dashboard docs to learn more.

Open

These updates have all been created already. Click a checkbox below to force a retry/rebase of any.

Detected dependencies

github-actions
.github/workflows/ci.yaml
  • actions/checkout v4@1d96c772d19495a3b5c517cd2bc0cb401ea0529f
  • actions/setup-go v5
  • golangci/golangci-lint-action v4
  • actions/checkout v4@1d96c772d19495a3b5c517cd2bc0cb401ea0529f
  • actions/setup-go v5
  • shogo82148/actions-goveralls v1
.github/workflows/release.yaml
  • actions/checkout v4@1d96c772d19495a3b5c517cd2bc0cb401ea0529f
  • anothrNick/github-tag-action 1.69.0
gomod
go.mod
  • go 1.19
  • github.com/aws/aws-lambda-go v1.47.0
  • github.com/hamba/logger/v2 v2.5.0
  • github.com/hamba/statter/v2 v2.3.4
  • github.com/json-iterator/go v1.1.12
  • github.com/stretchr/testify v1.9.0

  • Check this box to trigger a request for Renovate to run again on this repository

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.