Comparing strings in automation

I want to parse a telegram command which contains the operation to perform.
It can be either ‘on’ or ‘off’.
Using .split i’m able to parse the operation string and I have a variable containing it.
However, no matter what I do, the comparison to ‘on’ or ‘off’ fails.

Example command: /light_action_main_op_on

Here is the code:

    - service: script.turn_on
      data_template:
        entity_id: >
          {% set tokens = trigger.event.data['data'].split('/light_action_') %}
          {% set tokens = tokens[1].split("_op_") %}
          {% set operation = tokens[1] %}
          {% if operation == 'on' %}
            script.turn_on_light
          {% elif operation == 'off' %}
            script.turn_off_light
          {% else script.dummy %}
            script.dummy_script
          {% endif %}

I’ve tried printing the operation and it’s indeed on/off (with no whitespaces).
What am I missing?

So you’ll notice this right here is a syntax error.
But it’s not just that.
I have to change
{% if operation == 'on' %}
to
{% if 'on' in operation %}
That’s the only way I made this work

You can make this much simpler:

    - service: script.turn_on
      data_template:
        entity_id: >
          {% if trigger.event.data.data[-1] == 'n' %}
            script.turn_on_light
          {% else %}
            script.turn_off_light
          {% endif %}

In fact, you can even do this:

    - service_template: >
        {% if trigger.event.data.data[-1] == 'n' %}
          script.turn_on_light
        {% else %}
          script.turn_off_light
        {% endif %}

Of if you want to go crazy, even:

    - service_template: >
        script.turn_{{ trigger.event.data.data.split('_')[-1] }}_light
2 Likes

Thank you for the options :slight_smile: