custom_components/whatsapp_bridge_integration/__init__.py aktualisiert

This commit is contained in:
2026-04-14 13:39:51 +00:00
parent adfe5dfe9d
commit 276d4a63cb

View File

@@ -1,64 +1,31 @@
import logging import logging
import requests from homeassistant.core import HomeAssistant
import voluptuous as vol from .const import DOMAIN
from homeassistant.core import HomeAssistant, ServiceCall
from .const import DOMAIN, CONF_PHONE_NUMBER
_LOGGER = logging.getLogger(__name__) _LOGGER = logging.getLogger(__name__)
async def async_setup(hass: HomeAssistant, config: dict): async def async_setup(hass: HomeAssistant, config: dict):
"""Set up the WhatsApp Bridge component."""
# Diese Funktion muss existieren, auch wenn sie nur True zurückgibt
return True return True
async def async_setup_entry(hass: HomeAssistant, entry): async def async_setup_entry(hass: HomeAssistant, entry):
"""Set up WhatsApp Bridge from a config entry.""" """Set up entry and forward to sensor platform."""
# Lege die Daten im hass-Objekt ab
hass.data.setdefault(DOMAIN, {})
hass.data[DOMAIN][entry.entry_id] = entry.data
# Registriere den Dienst nur einmal # Forward the setup to the sensor platform to create entities
await hass.config_entries.async_forward_entry_setups(entry, ["sensor"])
# Registriere den Service (nur beim ersten Mal)
if not hass.services.has_service(DOMAIN, "send_message"): if not hass.services.has_service(DOMAIN, "send_message"):
from .services import async_setup_services
async def handle_send_message(call: ServiceCall): await async_setup_services(hass)
message = call.data.get("message")
recipient = call.data.get("recipient")
use_manual = call.data.get("use_manual_number", False)
target_number = call.data.get("number")
entries = hass.config_entries.async_entries(DOMAIN)
targets = []
# 1. Manuelle Nummer Priorität
if use_manual and target_number:
targets.append(target_number)
# 2. Rundruf an alle
elif recipient == "all_accounts":
for e in entries:
targets.append(e.data.get(CONF_PHONE_NUMBER))
# 3. Spezifischer Account aus Dropdown
elif recipient:
for e in entries:
if e.title.lower() == recipient.lower():
targets.append(e.data.get(CONF_PHONE_NUMBER))
# Sende-Vorgang
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)
)
_LOGGER.info("WhatsApp message successfully sent to %s", num)
except Exception as e:
_LOGGER.error("Failed to send WhatsApp to %s: %s", num, str(e))
hass.services.async_register(DOMAIN, "send_message", handle_send_message)
return True return True
async def async_unload_entry(hass: HomeAssistant, entry): async def async_unload_entry(hass: HomeAssistant, entry):
"""Unload a config entry.""" """Unload a config entry."""
return True unload_ok = await hass.config_entries.async_unload_platforms(entry, ["sensor"])
if unload_ok:
hass.data[DOMAIN].pop(entry.entry_id)
return unload_ok