Use script fields to form the service_template

I am trying to have a script that dynamically calls a notifer based on a field but I am getting the following error.

Error executing script script.notify_battery. Invalid data for call_service at pos 1: Service notify. does not match format <domain>.<name>

Automation

- alias: Notify Phone Battery
  trigger: 
    platform: numeric_state
    entity_id:
      - sensor.battery_chi
      - sensor.battery_bea
    below: 20
  action:
    service: script.notify_battery
    data:
      variables:
        notifier: "telegram_{{ trigger.entity_id.split('_')[-1] }}"
        battery_value: "{{ states('trigger.entity_id') }}"

Script

notify_battery:
  alias: 'Notify battery'
  description: 'Send notification on battery low'
  fields: 
    notifier:
      description: 'The notifier to send too'
      example: 'telegram_chi'
    battery_value:
      description: 'The value of the battery'
      example: '20'
  sequence:
    - service_template: >
        notify.{{ notifier }}
      data_template:
        title: 'You should think about charging your phone!'
        message: 'The battery has dropped  to {{ battery_value }}%'
  action:
    service: script.notify_battery
    data_template:
      notifier: "telegram_{{ trigger.entity_id.split('_')[-1] }}"
      battery_value: "{{ states('trigger.entity_id') }}"

EDIT: See Passing Variables to Scripts, especially the part that starts “The other way is …” :slight_smile:

Thanks for the inspiration… I changed it to

  action:
    service: script.notify_battery
    data:
      notifier: "telegram_{{ trigger.entity_id.split('_')[-1] }}"
      battery_value: "{{ states('trigger.entity_id') }}"

but using a mock service to mimic battery change and it worked… I should have read the docs properly!

Thanks so much for helping!

That won’t work. You need data_template, not data.

You were correct!

One part that’s still not working the value is being passed as “unknown” isn’t {{ states('trigger.entity_id') }} going to get the correct sensor value?

For example if I use {{ states('sensor.battery_chi') }} in the templating sandbox it works.

{{ states(trigger.entity_id) }}

I.e., remove the quotes. Sorry, missed that the first time.

Thanks! How did I miss that! I guess I was passing it as a string literal :frowning: