53 lines
2.0 KiB
Python
53 lines
2.0 KiB
Python
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 = []
|
|
|
|
# 1. Fall: Broadcast (Wenn "all" getippt wurde)
|
|
if recipient == "all":
|
|
entries = hass.config_entries.async_entries(DOMAIN)
|
|
for e in entries:
|
|
targets.append(e.data.get(CONF_PHONE_NUMBER))
|
|
|
|
# 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:
|
|
_LOGGER.error("Could not find phone number for entity: %s", recipient)
|
|
|
|
# 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:
|
|
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)
|
|
)
|
|
except Exception as e:
|
|
_LOGGER.error("Error sending to %s: %s", num, str(e))
|
|
|
|
hass.services.async_register(DOMAIN, "send_message", handle_send_message) |