Help with simplifying an automation

Hi All

I would love some help with simplifying the below code which dims my led light strip in my room so that it is at minimum brightness for the next morning when another similar automation brightens the lights gradually to wake me up. It works fine but takes up too many lines in my automations.yaml. I am not a very good programmer (electronics is my expertise) so I am appealing to you helpful and enthusiastic people out there. Thanks in advance.

- id: '1525515644688'
  alias: Go to Sleep Lights
  trigger:
    platform: event
    event_type: xiaomi_aqara.click
    event_data:
      entity_id: binary_sensor.switch_158d0001ae6c66
      click_type: single
  condition: []
  action:
  - data:
      entity_id: switch.light_bedroom_level
    service: switch.turn_off
  - delay:
      seconds: 0.5
  - data:
      entity_id: switch.light_bedroom_level
    service: switch.turn_off
  - delay:
      seconds: 0.5
  - data:
      entity_id: switch.light_bedroom_level
    service: switch.turn_off
  - delay:
      seconds: 0.5
  - data:
      entity_id: switch.light_bedroom_level
    service: switch.turn_off
  - delay:
      seconds: 0.5
  - data:
      entity_id: switch.light_bedroom_level
    service: switch.turn_off
  - delay:
      seconds: 0.5
  - data:
      entity_id: switch.light_bedroom_level
    service: switch.turn_off
  - delay:
      seconds: 0.5
  - data:
      entity_id: switch.light_bedroom_level
    service: switch.turn_off
  - delay:
      seconds: 0.5
  - data:
      entity_id: switch.light_bedroom_level
    service: switch.turn_off
  - delay:
      seconds: 0.5
  - data:
      entity_id: switch.light_bedroom
    service: switch.turn_off

There’s really not much you can do when you need to repeat a service. You could build a loop but it will take up more lines of code and your code will be fragmented. Your other option is a python script.

import time

entity_id = data.get("repeat_entity")
repeats = data.get("repeats", 1)
repeats = int(repeats) if not isinstance(repeats, int) else repeats
service = data.get("service")
service = int(service) if not isinstance(service, int) else service


if entity_id and service:
    for i in range(repeats):
        service_domain, service = service.split('.')
        data = { "entity_id" : entity_id }
        hass.services.call(service_domain, service, data)
        time.sleep(delay)

The service would be:

 - service: python_script.whatever_you_name_it
   data:
     repeat_entity: switch.light_bedroom_level
     repeats: 5
     service: switch.turn_off

You’ll need to follow the directions for installing python scripts

Hi Petro
Thanks for the quick reply, I see what you mean, I will just leave it as is then.
Cheers