Getting started with the Relay SDK — node.js edition

advertisement

Hey folks! Let’s get started with a quick example showing how you can use the Relay node.js SDK to create a simple number game. For this example, we’ll use Heroku to host a Websocket that will maintain a connection with the Relay Server.

First, create a new app using Heroku. We’ll be naming ours ‘relay-wf’:

Next, let’s setup our environment with git and Heroku CLI (instructions for windows/linux):

$ brew tap heroku/brew && brew install heroku
$ heroku login

Next, let’s initialize our environment:

$ cd relay-wf
$ git init
$ npm init
$ npm install relay-js

Next, we’ll setup our example interaction & deploy it to heroku. Here we are creating a basic app that let’s users guess two numbers and returns the one who guest closest

import relay from 'relay-js'const app = relay()app.workflow(`numbers`, workflow => {
relay.on(`start`, async () => {
const user = await relay.getDeviceName()
const random = Math.floor(Math.random() * 10) + 1
await relay.say(`Player One, pick a number between 1 and 10`)
const numberOne = await relay.listen(["$DIGIT_SEQUENCE"])
await relay.say(`Player Two, pick a number between 1 and 10`)
const numberTwo = await relay.listen(["$DIGIT_SEQUENCE"])
if (Math.abs(numberOne - random) < Math.abs(numberTwo - random)) {
await relay.say(`Player One wins! ${numberOne} was closest to ${random}!`)
} else {
await relay.say(`Player Two wins! ${numberTwo} was closest to ${random}!`)
}
await relay.terminate()
})
})

Next, we’ll add our workflow configuration to Relay servers. First, fire up Dash by going to api-dash.relaygo.com (for production, this is dash.relaygo.com) and navigate to the Workflows section and select the Create button for ‘Custom Workflow’ :

From there, you can enter your workflow configuration. This includes the name of your workflow (here we’ve named ours ‘numbers’), the devices you’d like it on (we’ll push to just one device here, ‘Ibraheem’) and URI hosting the workflow (relay-wf.herokuapp.com). We’re also using the spoken phrase ‘pick a number’ to initiate our workflow from the device.

Save your workflow and then let’s deploy our workflow node.js app to heroku:

$ git commit -am 'Initial deploy'
$ export HEROKU_APP=relay-wf
$ git push master heroku
$ heroku logs --tail

And that’s it! If everything worked, you should now be able to speak ‘pick a number’ into the Relay assistant and trigger your number game!

Ready to start developing with Relay? Click here to signup for our Relay SDK beta.

This content was originally published HERE

advertisement

Be the first to comment on "Getting started with the Relay SDK — node.js edition"

Leave a comment

Your email address will not be published.


*