Enhance notification message rendering by adding entity state resolution and regex pattern matching

This commit is contained in:
2026-06-17 19:19:25 +02:00
parent fd0769fd12
commit 9607e6e78d

View File

@@ -1,10 +1,13 @@
import appdaemon.plugins.hass.hassapi as hass import appdaemon.plugins.hass.hassapi as hass
import appdaemon.exceptions as ad_exception import appdaemon.exceptions as ad_exception
import ad_toolbox.smartcondition as SmartCondition import ad_toolbox.smartcondition as SmartCondition
import re
import uuid import uuid
from expressionparser import ParsingException from expressionparser import ParsingException
class Notification: class Notification:
ENTITY_PLACEHOLDER_PATTERN = re.compile(r"\{([^{}]+)\}")
def __init__(self,ad_api,config,name): def __init__(self,ad_api,config,name):
self.recipients = dict() self.recipients = dict()
self.config = config self.config = config
@@ -50,14 +53,40 @@ class Notification:
for service in recipient_yaml['services']: for service in recipient_yaml['services']:
clear_notification(service,tag) clear_notification(service,tag)
def render_message_content(self, content):
if not isinstance(content, str):
return content
def replace_entity_state(match):
entity_id = match.group(1).strip()
if entity_id == "":
return match.group(0)
try:
state = self.ad_api.get_state(entity_id)
except Exception as e:
self.log_error(f"Failed to resolve '{entity_id}' in notification content: {e}")
return match.group(0)
if state is None:
self.log_error(f"Unable to resolve '{entity_id}' in notification content")
return match.group(0)
return str(state)
return self.ENTITY_PLACEHOLDER_PATTERN.sub(replace_entity_state, content)
def send_notification(self,recipient): def send_notification(self,recipient):
try: title = self.config['message']['title'] try: title_template = self.config['message']['title']
except KeyError: title = "" except KeyError: title_template = ""
try: message = self.config['message']['content'] try: message_content = self.config['message']['content']
except KeyError: message = "" except KeyError: message_content = ""
try: data = self.config['message']['data'] try: data = self.config['message']['data']
except KeyError: data = dict() except KeyError: data = dict()
title = self.render_message_content(title_template)
message = self.render_message_content(message_content)
#TODO : maybe it's better to not send tag when it's not needed #TODO : maybe it's better to not send tag when it's not needed
if not 'tag' in data: if not 'tag' in data:
data['tag'] = self.uuid data['tag'] = self.uuid