A script to create a one-time notification on state change

I wrote a script to set up a one-time notification for when an entity changes state. The script accepts two parameters, the entity_id (to monitor; required) and the device (to notify; optional). If the device is not provided, the script uses the context.user_id parameter to guess the name of the notify service for that user’s mobile app.

I’m curious if there’s a better way to notify arbitrary users, using only the user_id.

Here is the full script.
alias: Notify on state change
fields:
  monitor_entity_id:
    name: Entity to monitor
    description: The entity_id to monitor for a state change.
    required: true
    selector:
      entity:
        multiple: false
  notify_device:
    name: Device to notify
    description: The device to notify on change.
    required: false
    selector:
      device:
        integration: mobile_app
        multiple: false
sequence:
  - alias: Set a templated variable
    variables:
      from_state: "{{ states(monitor_entity_id) }}"
      friendly_name: "{{ state_attr(monitor_entity_id,'friendly_name') }}"
      notify_service: >-
        notify.mobile_app_{{ device_attr(notify_device,'name') | replace('
        ','_') if notify_device is defined else (states.person |
        selectattr('attributes.user_id','defined') |
        selectattr('attributes.user_id','eq',context.user_id) |
        list)[0].attributes.source.split('.')[1] }}
  - wait_template: "{{ not is_state(monitor_entity_id,from_state) }}"
    continue_on_timeout: true
  - service: "{{ notify_service }}"
    data:
      message: "{{ from_state }} → {{ states(monitor_entity_id) }}"
      title: "State changed: {{ friendly_name }}"
mode: parallel
icon: mdi:bell-plus
max: 10
Example service call.
service: script.notify_on_state_change
data:
  monitor_entity_id: binary_sensor.pixel_4a_interactive
  notify_device: 22452example5854device2395id3193

notify_device is optional

One thing to note: the script will fail if you change the name of your mobile_app device without also updating the entity_ids associated with it (or if you customize the device_tracker entity_id). For example, I changed my device name from “Pixel 4a 5G” → “Pixel 4a” some time ago but did not want to lose my sensor history, so I didn’t update the entity_ids associated with it. However, the notify service still updated to notify.mobile_app_pixel_4a and the script failed when I called it because it was looking for notify.mobile_app_pixel_4a_5g.

It would be awesome if there was a way to return all devices associated with a user, like you’d find at /config/person when you select a person. Clearly that association is stored somewhere, but I don’t know where it is or how to access it in a template.