Please, I need help to make a template work in mqtt.publish

Hello everyone, I’m starting at home assistant, and I need a help with a script template sintax code.
I want that after the same command, according to which alexa he was given, a remote control of the living room or my room is used for a same script, for example, to return the TV channel (from the bedroom or living room) I created a script to choice between two IR.
Here is my sensors template:

- platform: template
  sensors:
    last_alexa:
      value_template: >
        {{ expand(states.group.all_echos) | selectattr('attributes.last_called','eq',True) | map(attribute='entity_id') | first }}

- platform: template
  sensors:
    ir_to_use:
      value_template: >
        {% if is_state("sensor.last_alexa", "media_player.echo_our_bedroom") %}
          tasm_cont_rem_our_bedroom_6b90ff
        {% else %}
          tasm_cont_rem_living_room_5e1299
        {% endif %}

and here is my problem with a sintax template, this script code wont work:

scr_tv_previous_chanel:
  alias: scr_ TV previous chanel
  sequence:
  - service: mqtt.publish
    data:
      topic: cmnd/{{ sensor.ir_to_use }}/IRsend
      payload: '{"Protocol":"SAMSUNG","Bits":32,"Data":"0xE0E008F7","Repeat":0}'

I also tested with data_template, and also

  - service: mqtt.publish
    data_template:
      topic: cmnd/"{{ sensor.ir_to_use }}"/IRsend
      payload: '{"Protocol":"SAMSUNG","Bits":32,"Data":"0xE0E008F7","Repeat":0}'

I made a code below that works, but I would like to use it as above:

   - service: mqtt.publish
     data:
       topic: >
         {% if is_state("sensor.last_alexa", "media_player.echo_our_bedroom”") %}
           cmnd/tasm_cont_rem_our_bedroom_6b90ff/IRsend
         {% else %}
           cmnd/tasm_cont_rem_living_room_5e1299/IRsend
         {% endif %}  
       payload: '{"Protocol":"SAMSUNG","Bits":32,"Data":"0xE0E008F7","Repeat":0}'

replace by

{{ states('sensor.ir_to_use') }}
2 Likes

Thank you @m0wlheld.

The script is working great now.

Please, one more
i want to use this template in the script below

- platform: template
  sensors:
    tv_to_use:
      value_template: >
        {% if is_state("sensor.last_alexa", "media_player.echo_our_bedroom") %}
          tv_our_bedroom
        {% else %}
          tv_living_room
        {% endif %}    

and this script, what do i have to change to work???

scr_tv_youtube:
  alias: scr_ TV -YOUTUBE
  sequence:
  - script.prepare_env_and_power_on_{{ states('sensor.tv_to_use') }}
  - service: media_player.play_media
    data_template:
      entity_id: media_player.{{ states('sensor.tv_to_use') }}
      media_content_id: 111299001912
      media_content_type: app

the script call prepare_env_and_power_on… and the media_player call above is not working.
it must be another syntax problem, but I couldn’t figure it out.