Until the bug is fixed, you can modify the template so that it excludes duplicates. To do that, use the unique filter.
In the following example, the unique filter is used to ensure all messages have a unique value of id. In other words, any message with a duplicate id value is discarded. This only needs to be done when a new message is added (not needed when a message is deleted).
template:
- trigger:
- platform: event
event_type:
- message_create
- message_delete
- message_delete_all
sensor:
- name: Messages
state: "{{ now().timestamp() | timestamp_custom() }}"
attributes:
messages: >
{% set msgs = this.attributes.get('messages', []) %}
{% if trigger.event.event_type == 'message_create' %}
{% set new = [{
"id": trigger.event.data.id | default('TS' ~ now().timestamp()),
"title": trigger.event.data.title | default(''),
"message": trigger.event.data.message | default(''),
"time": now().isoformat() }] %}
{{ (msgs + new) | unique(attribute='id') | list }}
{% elif trigger.event.event_type == 'message_delete' %}
{% if trigger.event.data.id is defined %}
{% set msgs = msgs | rejectattr('id', 'eq', trigger.event.data.id) | list %}
{% elif trigger.event.data.index is defined and trigger.event.data.index | is_number %}
{% set t = trigger.event.data.index | int(0) - 1 %}
{% if 0 <= t < msgs|count %}
{% set msgs = msgs | rejectattr('id', 'eq', msgs[t].id) | list %}
{% endif %}
{% endif %}
{{ msgs }}
{% else %}
{{ [] }}
{% endif %}
tl;dr
This discards duplicates:
{{ (msgs + new) | unique(attribute='id') | list }}