Using optional variables in scripts

Hi everyone,

after unsuccessfully searching the forum and documentation, does anybody have an idea how to use optional variables in a script? My situation: I have a script that accepts 4 different variables when being called, however, I would like to make some of those variables optional. The script broadcasts some messages on a media player and one variable is the volume to use when broadcasting the message. I would like a setting where I can just choose to not pass the volume variable and then the script identifying this and falling back to some default volume level. Would highly appreciate any guidance here.

Thanks!

I am not sure that the built in scripts can do what you are asking but Node-Red can. The more advanced rules engine would allow you to add all the inputs you want and then act if all or some of those inputs were modified. If Node-Red is anything you would be interested in I would be happy to try to help you get your script working.

You can do that by checking if the variable is defined and handling the situation when it’s not.

Here’s a simple example.

var_test:
  alias: Variable test
  sequence:
  - service: persistent_notification.create
    data:
      title: Hello
      message: "{{ msg if msg is defined else 'World!' }}"
  mode: single
  • If the variable msg is defined, it is used for the message option.
  • If the variable msg is not defined, a default value is used.

You can easily test the script by using Developer tools > Services and calling it with and without a msg variable.

3 Likes

Built in scripts can definitely do that, in fact I challenge you to provide an automation that can be done in Node-Red, but not with built-in automations/scripts.

Cool, I have no doubt there is a ton I do not know about HA and its capabilities. Since you worded your response that way, would you be willing to look at one of my Node-Red flows and see if you can show me how this would be accomplished with the built in scripts? I would like to gain a better understanding of their limitations.

Please open a separate topic for this analysis. Thank you.

You can open a separate topic and tag me there, however you’d need to explain the flow to me, as I’m not familiar with node-red flows.

Thanks! Will try that out tomorrow!

Did you get the chance to try it?

Thanks! Indeed worked very well, thanks again!

1 Like