Help with automation trigger random value

I want to generate a random offset on the trigger for an automation but I am getting an error. Any way to be able to accomplish this? Thanks in advance

- id: "Random Lights Turning On"
  trigger:
    platform: sun
    event: sunset
    offset: '00:{{(range(15, 30)|random|int)}}:00'
  action:
    - service: switch.turn_on
      entity_id: switch.lamp_relay

You can’t use a template with offset.

One workaround is to allow it to trigger at sunset and then use a delay in the action.

For example:

- id: "Random Lights Turning On"
  trigger:
  - platform: sun
    event: sunset
  action:
  - delay:
      minutes: '{{ range(15, 30) | random }}'
  - service: switch.turn_on
    target:
      entity_id: switch.lamp_relay

The drawback is that this technique only allows for a random delay after sunset (not before sunset).

Hi.

To have a random delay before sunset, can’t you use a fixed negative offset and then a random delay?

As I understand in the example above, the switch will be turned on 15 to 30 minutes after sunset.

If I want the switch to be triggered 15 to 30 minutes before sunset, i can offset 30 minutes and then a delay from 1 to 15 minutes.
My idea:

- id: "Random Lights Turning On"
  trigger:
  - platform: sun
    event: sunset
    offset: "-00:30:00"
  action:
  - delay:
      minutes: '{{ range(1, 15) | random }}'
  - service: switch.turn_on
    target:
      entity_id: switch.lamp_relay
1 Like

Sorry for the stupid question, but where do I have to put this script?
It is my first time that I am adding a script for automation

I would not use the term script to describe the code for the automation since there is an entity called script that is separate from automations. This code is the automation if you are writing the automation on the MQTT editor instead of using the UI. I hope I understood the question correctly.