50 lines
1.9 KiB
Python
50 lines
1.9 KiB
Python
import logging
|
|
import aiohttp
|
|
from homeassistant.core import HomeAssistant, ServiceCall
|
|
from homeassistant.exceptions import HomeAssistantError
|
|
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")
|
|
if not recipient or message is None:
|
|
raise HomeAssistantError("Empfänger und Nachricht sind erforderlich")
|
|
|
|
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)
|
|
|
|
api = hass.data[DOMAIN]["api"]
|
|
|
|
# Senden
|
|
for num in targets:
|
|
if not num: continue
|
|
try:
|
|
await api.async_send_message(num, message)
|
|
_LOGGER.info("WhatsApp sent to %s", num)
|
|
except (aiohttp.ClientError, TimeoutError, RuntimeError) as err:
|
|
_LOGGER.error("Error sending to %s: %s", num, err)
|
|
raise HomeAssistantError(
|
|
f"WhatsApp-Nachricht an {num} fehlgeschlagen: {err}"
|
|
) from err
|
|
|
|
hass.services.async_register(DOMAIN, "send_message", handle_send_message)
|