custom_components/whatsapp_bridge_integration/services.py aktualisiert

This commit is contained in:
2026-04-14 13:59:19 +00:00
parent 6b3a10bd33
commit 39df1ed0fa

View File

@@ -1,43 +1,53 @@
import requests import requests
import logging import logging
from homeassistant.core import HomeAssistant, ServiceCall from homeassistant.core import HomeAssistant, ServiceCall
from .const import DOMAIN from .const import DOMAIN, CONF_PHONE_NUMBER
_LOGGER = logging.getLogger(__name__) _LOGGER = logging.getLogger(__name__)
async def async_setup_services(hass: HomeAssistant): async def async_setup_services(hass: HomeAssistant):
async def handle_send_message(call: ServiceCall): async def handle_send_message(call: ServiceCall):
message = call.data.get("message") message = call.data.get("message")
target_entity = call.data.get("recipient") recipient = call.data.get("recipient")
targets = [] targets = []
# 1. Fall: Broadcast an alle # 1. Fall: Broadcast (Wenn "all" getippt wurde)
if target_entity == "all": if recipient == "all":
entities = hass.states.async_all("sensor") entries = hass.config_entries.async_entries(DOMAIN)
for entity in entities: for e in entries:
if entity.entity_id.startswith("sensor.whatsapp_"): targets.append(e.data.get(CONF_PHONE_NUMBER))
targets.append(entity.attributes.get("phone_number"))
# 2. Fall: Einzelne Entity ausgewählt # 2. Fall: Eine Entity wurde ausgewählt (z.B. sensor.whatsapp_rene)
elif recipient.startswith("sensor."):
state = hass.states.get(recipient)
if state and "phone_number" in state.attributes:
targets.append(state.attributes.get("phone_number"))
else: else:
state = hass.states.get(target_entity) _LOGGER.error("Could not find phone number for entity: %s", recipient)
if state:
num = state.attributes.get("phone_number")
if num:
targets.append(num)
else:
# Fallback für manuelle Eingabe in YAML
targets.append(target_entity)
# 3. Fall: Manuelle Nummer oder Name
else:
# Wir prüfen sicherheitshalber, ob es ein Account-Name ist
entries = hass.config_entries.async_entries(DOMAIN)
account_found = False
for e in entries:
if e.title.lower() == recipient.lower():
targets.append(e.data.get(CONF_PHONE_NUMBER))
account_found = True
break
if not account_found:
targets.append(recipient)
# Senden
for num in targets: for num in targets:
url = "http://866fd2eb-whatsapp-bridge:3000/send" url = "http://866fd2eb-whatsapp-bridge:3000/send"
try: try:
await hass.async_add_executor_job( await hass.async_add_executor_job(
lambda: requests.post(url, json={"number": num, "message": message}, timeout=10) lambda: requests.post(url, json={"number": num, "message": message}, timeout=10)
) )
_LOGGER.info("Sent to %s", num)
except Exception as e: except Exception as e:
_LOGGER.error("Error: %s", str(e)) _LOGGER.error("Error sending to %s: %s", num, str(e))
hass.services.async_register(DOMAIN, "send_message", handle_send_message) hass.services.async_register(DOMAIN, "send_message", handle_send_message)