How to use trigger entity_id friendly_name?

Hi All

I have create this automation that when someone press the xiaomi button i will get a notification on telegram

my issue is that i have lots of buttons and i don’t want to make an automation for each one

i know that i need to change this line

title: ' {{ states.binary_sensor.switch_15000001e007ae.name }} '

but i have no idea to what :frowning: i am guessing that it’s something like this

title: ' {{ states.the_trigger_entity_id.name }} '

but of course this is not the right syntax

here is the full automation if you need it

- id: aaaaa
  alias: aaaaa
  trigger:
    - platform: event
      event_type: xiaomi_aqara.click
      event_data:
        entity_id: binary_sensor.switch_15000001e007ae
        click_type: single
    - platform: event
      event_type: xiaomi_aqara.click
      event_data:
        entity_id: binary_sensor.switch_1500000200abed
        click_type: single
  action:
    - service: notify.telegram
      data_template:
        title: ' {{ states.binary_sensor.switch_15000001e007ae.name }} '
        message: "single press"

Thank you very much for you help

btw: i tried
{{ trigger.from_state.attributes.friendly_name }}
{{ trigger.to_state.attributes.friendly_name }}
{{ trigger.to_state.state }}
{{ trigger.to_state.name }}
and it didn’t worked

1 Like

Try:

        title: " {{ state_attr(trigger.event.data.entity_id, 'friendly_name') }} "

EDIT: Per @petro’s post the quotes were wrong. Fixed.

first of all Thanks for your help but i got this on check config:

Error loading /config/configuration.yaml: while parsing a block mapping
in “/config/automations.yaml”, line 149, column 9
expected , but found ‘’
in “/config/automations.yaml”, line 149, column 63

change the outside quotes to double

       title: "{{ state_attr(trigger.event.data.entity_id, 'friendly_name') }}"
5 Likes

wow you are like HA Ninja thank you so much :smile:

i will ask you another one (it looks like my question is a walk in the park for you)

is there a way to make this shorter and not duplicate this for every switch ?

- platform: event
  event_type: xiaomi_aqara.click
  event_data:
    entity_id: binary_sensor.switch_158000000807ae
    click_type: single
- platform: event
  event_type: xiaomi_aqara.click
  event_data:
    entity_id: binary_sensor.switch_1580000003abed
    click_type: single

Assuming you want to trigger with the event type being xiaomi_aqara.click and click_type equal to single when click_type is in the event data (i.e., no matter what entity_id is in event data), then:

- platform: event
  event_type: xiaomi_aqara.click
  event_data:
    click_type: single

wow you are the best.

Thanks a lot for your help,
may your house in heaven will be automated using HA :smile:

1 Like

I wonder if you can solve this one as your solution does not work for my entity.
I have a binary_sensor.curtain_not_needed which is a trend sensor on sensor.bedroom_window_temp.
It is one of several triggers in an automation and I want to know which entity_id triggered.
I have these facts: (I am using persistent_notification message to retrieve)

trigger.entity_id: binary_sensor.curtain_not_needed 
trigger.to_state: <state binary_sensor.curtain_not_needed=on; entity_id=sensor.bedroom_window_temp, friendly_name=curtain_not_needed, gradient=-0.003124310251228358, invert=False, min_gradient=-0.0033, sample_count=1, sample_duration=120, device_class=cold @ 2020-05-11T18:31:08.223690+10:00>
trigger.to_state.state: on ;

However adding {{ state_attr(trigger.event.data.entity_id, ‘friendly_name’) }}
results in a log entry of:


Developer Tools
test curtain: Error executing script. Unexpected error for call_service at pos 1: Error rendering data template: UndefinedError: 'dict object' has no attribute 'state'
6:27:28 PM – Automation (ERROR) - message first occurred at 6:07:35 PM and shows up 6 times
Updating rest sensor took longer than the scheduled update interval 0:00:01
6:27:06 PM – Sensor (WARNING) - message first occurred at 6:04:05 PM and shows up 6 times
Updating device list from legacy took longer than the scheduled scan interval 0:00:12
6:27:06 PM – Device tracker (WARNING) - message first occurred at 6:03:36 PM and shows up 24 times
Config entry for upnp not ready yet. Retrying in 80 seconds.
6:26:24 PM – config_entries.py (WARNING) - message first occurred at 6:03:39 PM and shows up 16 times
Wanted UPnP/IGD device with UDN "uuid:0065b8f9-9ecd-4c26-8008-94a1115c0e20" not found, aborting
6:26:24 PM – UPnP (WARNING) - message first occurred at 6:03:39 PM and shows up 16 times
Error during template condition: UndefinedError: 'binary_sensor' is undefined
6:21:39 PM – helpers/condition.py (ERROR) - message first occurred at 6:06:39 PM and shows up 4 times
Detected I/O inside the event loop. This is causing stability issues. Please report issue to the custom component author for willyweather doing I/O at custom_components/willyweather/weather.py, line 209: result = requests.get(self._build_url(), timeout=10).json()
6:09:08 PM – util/async_.py (WARNING)
Error doing job: Exception in callback async_track_state_change.<locals>.state_change_listener(<Event state_...124731+10:00>>) at /usr/src/homeassistant/homeassistant/helpers/event.py:81
6:08:29 PM – helpers/template.py (ERROR)
 
Log Details (ERROR)
Logger: homeassistant.components.automation
Source: helpers/service.py:135
Integration: Automation (documentation, issues)
First occurred: 6:07:35 PM (6 occurrences)
Last logged: 6:27:28 PM

test curtain: Error executing script. Unexpected error for call_service at pos 1: Error rendering data template: UndefinedError: 'dict object' has no attribute 'state'
test curtain: Error executing script. Unexpected error for call_service at pos 1: Error rendering data template: UndefinedError: 'dict object' has no attribute 'event'
test curtain: Error executing script. Unexpected error for call_service at pos 1: Error rendering data template: UndefinedError: 'homeassistant.core.State object' has no attribute 'event'
Traceback (most recent call last):
  File "/usr/src/homeassistant/homeassistant/helpers/template.py", line 222, in async_render
    return compiled.render(kwargs).strip()
  File "/usr/local/lib/python3.7/site-packages/jinja2/environment.py", line 1090, in render
    self.environment.handle_exception()
  File "/usr/local/lib/python3.7/site-packages/jinja2/environment.py", line 832, in handle_exception
    reraise(*rewrite_traceback_stack(source=source))
  File "/usr/local/lib/python3.7/site-packages/jinja2/_compat.py", line 28, in reraise
    raise value.with_traceback(tb)
  File "<template>", line 1, in top-level template code
  File "/usr/local/lib/python3.7/site-packages/jinja2/sandbox.py", line 407, in getattr
    value = getattr(obj, attribute)
jinja2.exceptions.UndefinedError: 'dict object' has no attribute 'state'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/usr/src/homeassistant/homeassistant/helpers/service.py", line 132, in async_prepare_call_from_config
    template.render_complex(config[CONF_SERVICE_DATA_TEMPLATE], variables)
  File "/usr/src/homeassistant/homeassistant/helpers/template.py", line 71, in render_complex
    return {key: render_complex(item, variables) for key, item in value.items()}
  File "/usr/src/homeassistant/homeassistant/helpers/template.py", line 71, in <dictcomp>
    return {key: render_complex(item, variables) for key, item in value.items()}
  File "/usr/src/homeassistant/homeassistant/helpers/template.py", line 73, in render_complex
    return value.async_render(variables)
  File "/usr/src/homeassistant/homeassistant/helpers/template.py", line 224, in async_render
    raise TemplateError(err)
homeassistant.exceptions.TemplateError: UndefinedError: 'dict object' has no attribute 'state'

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "/usr/src/homeassistant/homeassistant/helpers/script.py", line 153, in _async_step
    self, f"_async_{cv.determine_script_action(self._action)}_step"
  File "/usr/src/homeassistant/homeassistant/helpers/script.py", line 623, in _async_call_service_step
    *self._prep_call_service_step(), blocking=True, context=self._context
  File "/usr/src/homeassistant/homeassistant/helpers/script.py", line 252, in _prep_call_service_step
    return async_prepare_call_from_config(self._hass, self._action, self._variables)
  File "/usr/src/homeassistant/homeassistant/helpers/service.py", line 135, in async_prepare_call_from_config
    raise HomeAssistantError(f"Error rendering data template: {ex}") from ex
homeassistant.exceptions.HomeAssistantError: Error rendering data template: UndefinedError: 'dict object' has no attribute 'state'

that trigger will only work with an event trigger. you have to post your automation to figure out how to change the code to match the trigger.

The driving force to get a grip of this is the following cut-down automation.

If the sensor triggers then trigger.entity_id contains the name of the sensor, but if the ‘time’ triggers it it is blank. 1) I can’t work out how to test for the trigger.entity_id being blank, 2) I was trying to find the trigger name if it was time doing it.
So I found your idea of {{ state_attr(trigger.event.data.entity_id, ‘friendly_name’) }} and adding that to the message induces the error above.

  trigger:
    - platform: state
      entity_id: binary_sensor.curtain_not_needed
      to: "on"
    - platform: sun
      event: sunset
      offset: "-00:30:00"
    - platform: time
      at: "08:30:00"
    - service: notify.pushover
      data_template:
        message: >
          Opening curtains. Triggered by {% if trigger.entity_id !='' %} '{{trigger.entity_id}}' {%else%} Time: {{now().time}} {%endif%} 

trigger.platform will indicate which type of trigger occurred, and hence, what other fields of the trigger variable are available. See Available Trigger Data.

So, e.g., you could do:

  trigger:
    - platform: state
      entity_id: binary_sensor.curtain_not_needed
      to: "on"
    - platform: sun
      event: sunset
      offset: "-00:30:00"
    - platform: time
      at: "08:30:00"
  action:
    - service: notify.pushover
      data_template:
        message: >
          Opening curtains. Triggered by
          {% if trigger.platform == 'state' %}
            {{ trigger.entity_id }}
          {% elif trigger.platform == 'sun' %}
            sunset
          {% else %}
            time {{ trigger.now }}
          {% endif %}
2 Likes

Taking a chance hoping that you see this :slight_smile:

Would you mind having a quick look at this? Should be identical to the example in this thread but gives me nothing:

- id: '1592204949949'
  alias: TEST - Entity ID notis
  description: ''
  trigger:
  - entity_id: binary_sensor.openclose_7
    platform: state
    to: 'on'
  condition: []
  action:
    - service: notify.mobile_app_johan
      data_template:
        message: Test
        title: "{{ state_attr(trigger.event.data.entity_id, 'friendly_name') }}"

Removing the title line gives me an instant notification. Any ideas?

Your trigger is not an event trigger. It’s a state trigger. This is explained here.

"{{ state_attr(trigger.to_state.entity_id, 'friendly_name') }}"

This should also work:

"{{ trigger.to_state.attributes.friendly_name }}"

or even:

"{{ trigger.to_state.name }}"
1 Like

Yes, it worked! Thanks! :smiley:

Before I spend way too many evenings on getting this to work in the automation I originally had in mind, do you think this scenario would be doable?

I have several plant sensors and what I want to accomplish is having one automation for all of them instead of individual automations. So when moisture < 25 I’d like to get a notification with the name of the sensor and the moisture level. I’m triggering on numerical value.

Should I continue working on this or is it a dead end you think?

  - platform: miflora
    mac: 'c4:7c:8d:62:1b:53'
    monitored_conditions:
      - moisture
      - light
      - temperature
      - conductivity
      - battery
    name: 'Mango 1'
    scan_interval: 7000  
- trigger:
  - platform: numeric_state
    entity_id:
    - sensor.plant1
    - sensor.plant2
    - sensor.plant3
    below: 25
  action:
  - service: notify.mobile_app_johan
    data_template:
      message: >
        Moisture too low for {{ trigger.to_state.name }}: {{ trigger.to_state.state }}
1 Like

Beautiful - it worked! Finally understand how these work now :slight_smile:

1 Like