Hi, I thought I’d share my script for managing items in a todo list.
This script can add or remove an item from a list and can be called in an automation or another script. One feature I wanted was to check if the item is already on the list before adding it to avoid duplicates. Similarly, it checks if the item is present before removing it, preventing errors in automations. This is my first script using variables, Ive seen some do one or the other but not both.so I hope it helps!
disclaimer this code is a mix of different bits ive found on the forum and chatGBT.
alias: Manage Item in List
sequence:
- target:
entity_id: "{{ list }}"
response_variable: todo
action: todo.get_items
- variables:
result: >
{% set items = todo[list]['items'] | map(attribute='summary') | list %}
{% set item_exists = item in items %} {% set item_details =
todo[list]['items'] | selectattr('summary', 'eq', item) | list | first |
default({}) %} {{ {'exists': item_exists, 'item': item_details} }}
- choose:
- conditions:
- condition: template
value_template: "{{ action == 'add' and not result.exists }}"
sequence:
- target:
entity_id: "{{ list }}"
data:
item: "{{ item }}"
action: todo.add_item
- conditions:
- condition: template
value_template: "{{ action == 'remove' and result.exists }}"
sequence:
- action: todo.remove_item
target:
entity_id: "{{ list }}"
data:
item: "{{ item }}"
mode: single
fields:
action:
name: Action
description: Choose whether to Add or Remove the Item
selector:
select:
options:
- add
- remove
required: true
item:
name: Item
description: The Item You Want to Manage
selector:
text: null
default: Item
required: true
list:
name: List
description: The List to which you want to Add or Remove the Item
selector:
entity:
domain: todo
required: true