Create a Game Night Record

Write the Script

Now that you’ve gotten Violet to tell you about your data, it’s time to update the gameNight.js file to let you create a new game night by voice command. 

In order to add our new functionality we are going to replace everything in gameNight.js with the following code.

var violet = require('violet').script();

///////////////////////////////////
// Integration and Business Logic
///////////////////////////////////

// Setup Store
var violetStoreSF = require('violet/lib/violetStoreSF')(violet);

// Utilities
var monthNames = [
    "January", "February", "March", "April", "May", "June",
    "July", "August", "September", "October", "November", "December"
  ];
var weekDays = {
  sunday: 0,
  monday: 1,
  tuesday: 2,
  wednesday: 3,
  thursday: 4,
  friday: 5,
  saturday: 6
}
var getDay = (dateTime)=>{
  return `${dateTime.getDate()} ${monthNames[dateTime.getMonth()]}`;
};
var getTime = (dateTime)=>{
  var hh = dateTime.getHours();
  var mm = dateTime.getMinutes();
  var ampm = 'am';
  if (hh>12) {
    hh-=12;
    ampm = 'pm';
  }
  if (mm==0) {
    mm = '';
  } else if (mm<10) {
    mm = 'Oh ' + mm; // Zero is pronounced as Oh when saying the time
  }
  return `${hh} ${mm} ${ampm}`;
};
var calcDateInFuture = (dayOfWeekStr, timeInPMStr)=>{
  var dt = new Date();

  var dayOfWeek = weekDays[dayOfWeekStr.toLowerCase()]
  if (dayOfWeek < dt.getDay()) dayOfWeek += 7;

  dt.setDate(dt.getDate() + dayOfWeek - dt.getDay());

  dt.setHours(parseInt(timeInPMStr) + 12);
  dt.setMinutes(0);
  dt.setSeconds(0);
  dt.setMilliseconds(0);

  return dt;
};

// Hook up the Script
var app = {
  getPastGameNights: (response)=>{
    return response.load({
      query: 'Id, Duration__c, Food__c, Game__c, Name, Start_Time__c FROM Game_Night__c WHERE Start_Time__c < TODAY'
    }).then((results)=>{
      if (results.length == 0) {
        response.say(`Sorry, I did not have anything scheduled`);
      } else {
        var dt = new Date(results[0].get('start_time__c'));
        response.say(`I had a game night scheduled on ${getDay(dt)} at ${getTime(dt)} where ${results[0].get('game__c')} was played`);
      }
    });
  },
  getUpcomingGameNights: (response)=>{
    return response.load({
      query: 'Id, Duration__c, Food__c, Game__c, Name, Start_Time__c FROM Game_Night__c WHERE Start_Time__c >= TODAY'
    }).then((results)=>{
      if (results.length == 0) {
        response.say(`Sorry, I do not have anything scheduled`);
      } else {
        var dt = new Date(results[0].get('start_time__c'));
        response.say(`I have a game night scheduled on ${getDay(dt)} at ${getTime(dt)} to play ${results[0].get('game__c')}`);
      }
    });
  },
  createGameNight: (response)=>{
    var dt = calcDateInFuture(response.get('day'), response.get('time'));
    return response.store('Game_night', {
      'name*': 'Game Night created by Violet',
      start_time: dt,
      duration: parseInt(response.get('duration')),
      game: response.get('game'),
      food: response.get('food')
    });
  }
}

///////////////////////////////////
// The Voice Script
///////////////////////////////////

violet.addInputTypes({
  "day": {
    type: "dayType",
    values: ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday"]
  },
  "time": "number",
  "duration": "number",
  "game": "phrase",
  "food": "phrase",
});

violet.addFlowScript(`
<app>
  <choice id="launch">
    <expecting>What can you do</expecting>
    <say>I can help you with planning Game Nights</say>
  </choice>

  <choice id="list">
    <expecting>What game nights have already been planned</expecting>
    <say>Sure</say>
    <decision>
      <prompt>Would you like to hear of game nights that are upcoming or in the past</prompt>
      <choice>
        <expecting>{In the|} past</expecting>
        <resolve value="app.getPastGameNights(response)"/>
      </choice>
      <choice>
        <expecting>Upcoming</expecting>
        <resolve value="app.getUpcomingGameNights(response)"/>
      </choice>
    </decision>
  </choice>

  <dialog id="create" elicit="dialog.nextReqdParam()">
    <expecting>I'm looking to organize a game night {this [[day]]|}</expecting>
    <item name="day" required>
      <ask>What day would you like it to be on?</ask>
      <expecting>{I'd like it to be]} this [[day]]</expecting>
    </item>
    <item name="duration" required>
      <ask>How long would you like it to be?</ask>
      <expecting>[[duration]] hours</expecting>
    </item>
    <item name="game" required>
      <ask>What would you like the main game to be</ask>
      <expecting>[[game]]</expecting>
    </item>
    <item name="food" required>
      <ask>Do you want snacks, lunch or dinner?</ask>
      <expecting>{everyone wants|} [[food]]</expecting>
    </item>
    <resolve value="app.createGameNight(response)">
      <say>Great, you are all set</say>
    </resolve>
  </dialog>

  <choice id="update">
    <expecting>Update</expecting>
    <expecting>Delete</expecting>
    <say>...</say>
  </choice>

</app>`, {app});

In this script you’ve added a large section of code to make sure Violet properly creates a new Game Night. If you take a look at the code, you can see it adds a new function called createGameNight. This function takes everything you’ve said and saved it. 

With this script, you double the amount of dialog and functionality you can expect from your app! 

Deploy and Test

We want to rebuild our app, so in Terminal/Command Prompt, enter the following.

node server.js

Note

Note

If for some reason you closed your terminal window, you have to navigate to the correct directory again and rerun the export/set commands before rebuilding the app. If you're already running node.js from the previous step, you won't see any response. But don't worry, your new code is now running!

Now navigate back to your web browser and go to http://localhost:8080/violet/trailhead. This takes you to the start page of your application, where you can now test the create aspect of your script. 

  1. Select your first intent, I'm looking to organize a game night {this [[day]]}.
  2. To the Slot Values date section, add the date 11.12.2028.
  3. Press Send Request.
  4. Violet responds with <speak>How long would you like it to be?</speak>.
  5. Select the intent that ends with {duration} hours as your next intent.
  6. To the Slot Values duration section, add 4.
  7. Press Send Request.
  8. Violet responds with <speak>What would you like the main game to be</speak>.
  9. Select the intent that ends with {game} as your next intent.
  10. To the Slot Values game section, add Trailhead.
  11. Press Send Request.
  12. Violet responds with <speak>Do you want snacks, lunch or dinner?</speak>.
  13. Select the intent that ends with everyone wants {food}, {food} as your next intent.
  14. To the Slot Values food section, add Snacks.
  15. Press Send Request.
  16. Violet responds with <speak>Great, you are all set</speak>.

Now you have told Violet about the game night you want to create, so let’s go check in Salesforce to make sure it added the data you were expecting.

  1. In Salesforce Click the app launcher App Launcher icon  and select Game Nights.
  • Depending on your Playground environment, you may have to search for the object by entering Game Nights in the launcher search field.
  1. Select the most recently viewed record (this should be the record you just created).
  2. If everything went well, you should see a record with:
    1. Game Night Name set as Game Night created by Violet.
    2. Duration of 4.00.
    3. Trailhead as the Game.
    4. Snacks as the Food.

A newly created game night record with randomly generated game night name and data corresponding to the previous steps above.

What’s Next?

Now that you have a node app running locally, you can choose to deploy it to Heroku using the documentation here. Once your application lives on Heroku you can link it to Alexa or Google Assistant using the instructions on your Violet application. There is a tab for Amazon Alexa and a tab for Google Dialog flow.

Summary

Congratulations! You’ve just learned how to create a simple voice application with just a few clicks and some code. You were able to ask Violet about the data in your org and create new data. 

This is just the surface of everything you can do with Violet, and we encourage you to learn even more, keep creating, and dive into our documentation. Violet is an open source project and you can contribute to the project here.

retargeting