import requests import logging from homeassistant.core import HomeAssistant, ServiceCall from .const import DOMAIN, CONF_PHONE_NUMBER _LOGGER = logging.getLogger(__name__) async def async_setup_services(hass: HomeAssistant): async def handle_send_message(call: ServiceCall): message = call.data.get("message") recipient = call.data.get("recipient") targets = [] entries = hass.config_entries.async_entries(DOMAIN) # 1. Prüfen, ob es eine Entity-ID ist if recipient.startswith("sensor."): state = hass.states.get(recipient) if state: # Ist es die 'All Accounts' Entität? if state.attributes.get("is_broadcast"): for e in entries: targets.append(e.data.get(CONF_PHONE_NUMBER)) else: # Es ist ein einzelner Account targets.append(state.attributes.get("phone_number")) # 2. Fallback: Manuelle Nummer (wenn keine sensor-ID übergeben wurde) else: targets.append(recipient) # Senden for num in targets: if not num: continue url = "http://866fd2eb-whatsapp-bridge:3000/send" try: await hass.async_add_executor_job( lambda: requests.post(url, json={"number": num, "message": message}, timeout=10) ) _LOGGER.info("WhatsApp sent to %s", num) except Exception as e: _LOGGER.error("Error sending to %s: %s", num, str(e)) hass.services.async_register(DOMAIN, "send_message", handle_send_message)