Perform action if there is a calendar event in the next X hours?

What is the “correct” way to have an action happen if there is an event in a calendar in the next X hours? Currently I have the following, which is a bit of a hacky workaround:

alias: "Octopus: Set max battery to 55% if free session next day"
description: ""
triggers:
  - trigger: time
    at: "23:29:00"
actions:
  - action: calendar.get_events
    data:
      duration:
        hours: 23
        minutes: 0
        seconds: 0
    target:
      entity_id:
        - calendar.octopus_energy_a_xxxxxxxx_octoplus_free_electricity_session
    response_variable: session_list
  - variables:
      free_session: >-
        {{session_list['calendar.octopus_energy_a_xxxxxxxx_octoplus_free_electricity_session']['events'][0]}}
  - action: notify.mobile_app_xxxx
    metadata: {}
    data:
      message: "{{free_session['start']|as_datetime}}"
      title: Octopus Free Session
  - action: input_number.set_value
    metadata: {}
    data:
      value: 55
    target:
      entity_id: input_number.maximum_house_battery_charge
mode: single

If there is a calendar event in the next 23 hours, the actions both happen as expected. If not, the “notify” action errors (because free_session['start'] is null), so the final action doesn’t happen. It works, but ugh.

Is there a better way to do this?

Use a condition.

alias: "Octopus: Set max battery to 55% if free session next day"
description: ""
triggers:
  - trigger: time
    at: "23:29:00"
actions:
  - action: calendar.get_events
    data:
      duration:
        hours: 23
        minutes: 0
        seconds: 0
    target:
      entity_id:
        - calendar.octopus_energy_a_xxxxxxxx_octoplus_free_electricity_session
    response_variable: session_list
  - variables:
      events: |
        {{ session_list['calendar.octopus_energy_a_xxxxxxxx_octoplus_free_electricity_session']['events'] }}
  - condition: template
    value_template: "{{ events|count > 0 }}"
  - action: notify.mobile_app_xxxx
    metadata: {}
    data:
      message: "{{ events[0]['start']|as_datetime }}"
      title: Octopus Free Session
  - action: input_number.set_value
    metadata: {}
    data:
      value: 55
    target:
      entity_id: input_number.maximum_house_battery_charge
mode: single
1 Like