Logic and Conditions
Sometimes building your logic you may want to execute some steps conditionally.
A good example is greeting a complete new user of your Alexa Skill / Google Action. You may want to onboard a new user a little bit, explain how your skill or action works. To do that you can use the concept of conditional steps.
Consider the following example:
- name: First Time User Welcome Step
# The actions of this step will only be executed
# when returning_user variable DOES NOT exist yet
when: 'returning_user is not defined'
actions:
- sendText: "Let's welcome our first time user! "
# Setting a context variable returning_user to true
- set: 'returning_user = true'
- sendText: 'Do you want to continue?'
- getInput:
next:
yes_next: Start of the Scenario Logic
no_thanks: Exit
AMAZON.CancelIntent: Exit
AMAZON.StopIntent: Exit
AMAZON.HelpIntent: Help
# The counter-part of WHEN is ELSE
# The execution will continue to the step Returning User Welcome Step
# When the variable returning_user DOES exist
else: Returning User Welcome Step
- name: Returning User Welcome Step
# The actions inside this step will execute
# only when the variable returning_user equals true
when: 'returning_user == true'
actions:
- sendText: "Let's welcome our returning user! "
next:
else: Start of the Scenario Logic
- name: Start of the Scenario Logic
actions:
- sendText: 'Let us start with the scenario logic right here!'
next: Exit
We tried to put the basic decision making logic in the comments inside of this scenario. Here is just a quick overview of what is happening in the text form:
- When the user starts the skill / action the first step
First Time User Welcome Step
is executed - Before any of the actions INSIDE of this steps are executed, the condition after the
when
statement is evaluated. In this case - the condition is the existence of the variable that we evaluate with theis not
syntax.
- WHEN the condition is true and variable
returning_user
doesn’t exist - everything inside of theactions
section is executed:- The user hears the text “Let’s welcome our first time user!”
- We set the the variable
returning_user
totrue
- We ask a user ‘Do you want to continue?’
- We are waiting for the user’s response with
getInput
- ELSE everything inside of the
actions
section is skipped and BotTalk jumps directly to theelse
built-in intent. Which is linked to theReturning User Welcome Step
- In the
Returning User Welcome Step
we demonstrate that everything you put inside of thewhen
condition will be interpreted as a TWIG expressions. This step also demonstrates another important concept. If the expression inside of thewhen
statement will be evaluated asfalse
, the wholeactions
section will be skipped - and BotTalk will move to thenext
section.