8 Commits
0.1.3 ... 0.1.5

5 changed files with 105 additions and 57 deletions

View File

@@ -1,36 +1,31 @@
async def handle_send_message(call: ServiceCall): import logging
message = call.data.get("message") from homeassistant.core import HomeAssistant
recipient = call.data.get("recipient") from .const import DOMAIN
use_manual = call.data.get("use_manual_number", False)
target_number = call.data.get("number")
entries = hass.config_entries.async_entries(DOMAIN)
targets = []
# Logik-Prüfung
if use_manual and target_number:
# Fall A: Manuelle Nummer
targets.append(target_number)
elif recipient == "all_accounts":
# Fall B: Rundruf
for e in entries:
targets.append(e.data.get(CONF_PHONE_NUMBER))
elif recipient:
# Fall C: Spezifisches Profil (Recipient Name)
for e in entries:
if e.title.lower() == recipient.lower():
targets.append(e.data.get(CONF_PHONE_NUMBER))
# Senden (wie gehabt) _LOGGER = logging.getLogger(__name__)
for num in targets:
url = "http://866fd2eb-whatsapp-bridge:3000/send" async def async_setup(hass: HomeAssistant, config: dict):
try: return True
await hass.async_add_executor_job(
lambda: requests.post(url, json={ async def async_setup_entry(hass: HomeAssistant, entry):
"number": num, """Set up entry and forward to sensor platform."""
"message": message # Lege die Daten im hass-Objekt ab
}, timeout=10) hass.data.setdefault(DOMAIN, {})
) hass.data[DOMAIN][entry.entry_id] = entry.data
_LOGGER.info("WhatsApp sent to %s", num)
except Exception as e: # Forward the setup to the sensor platform to create entities
_LOGGER.error("Error sending to %s: %s", num, str(e)) 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"):
from .services import async_setup_services
await async_setup_services(hass)
return True
async def async_unload_entry(hass: HomeAssistant, entry):
"""Unload a config entry."""
unload_ok = await hass.config_entries.async_unload_platforms(entry, ["sensor"])
if unload_ok:
hass.data[DOMAIN].pop(entry.entry_id)
return unload_ok

View File

@@ -4,7 +4,7 @@
"documentation": "https://git.bahmcloud.de/bahmcloud/Whatsapp-Bridge-Integration", "documentation": "https://git.bahmcloud.de/bahmcloud/Whatsapp-Bridge-Integration",
"dependencies": [], "dependencies": [],
"codeowners": ["@bahmcloud"], "codeowners": ["@bahmcloud"],
"version": "0.1.3", "version": "0.1.5",
"iot_class": "local_polling", "iot_class": "local_polling",
"config_flow": true "config_flow": true
} }

View File

@@ -0,0 +1,22 @@
from homeassistant.components.sensor import SensorEntity
from .const import DOMAIN, CONF_ACCOUNT_NAME
async def async_setup_entry(hass, entry, async_add_entities):
"""Add a sensor for each WhatsApp account."""
async_add_entities([WhatsAppAccountEntity(entry)], True)
class WhatsAppAccountEntity(SensorEntity):
"""Representation of a WhatsApp Account as an entity."""
def __init__(self, entry):
self._entry = entry
self._attr_name = f"WhatsApp {entry.title}"
self._attr_unique_id = f"{entry.entry_id}_status"
self._attr_icon = "mdi:whatsapp"
# Wir speichern die Nummer in den Attributen, damit der Service sie findet
self._attr_extra_state_attributes = {
"phone_number": entry.data.get("phone_number")
}
@property
def state(self):
return "Ready"

View File

@@ -0,0 +1,43 @@
import requests
import logging
from homeassistant.core import HomeAssistant, ServiceCall
from .const import DOMAIN
_LOGGER = logging.getLogger(__name__)
async def async_setup_services(hass: HomeAssistant):
async def handle_send_message(call: ServiceCall):
message = call.data.get("message")
target_entity = call.data.get("recipient")
targets = []
# 1. Fall: Broadcast an alle
if target_entity == "all":
entities = hass.states.async_all("sensor")
for entity in entities:
if entity.entity_id.startswith("sensor.whatsapp_"):
targets.append(entity.attributes.get("phone_number"))
# 2. Fall: Einzelne Entity ausgewählt
else:
state = hass.states.get(target_entity)
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)
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("Sent to %s", num)
except Exception as e:
_LOGGER.error("Error: %s", str(e))
hass.services.async_register(DOMAIN, "send_message", handle_send_message)

View File

@@ -1,33 +1,21 @@
send_message: send_message:
name: Send Message name: Send Message
description: Sends a WhatsApp message via the Bahmcloud Bridge. description: Sends a WhatsApp message.
fields: fields:
recipient: recipient:
name: Recipient name: Recipient
description: Select a saved profile or choose "Broadcast to all". description: Select an account or enter a manual number/ID.
required: true required: true
selector: selector:
select: text: {} # Easy Entry from some custom Numbers
options: entity:
- label: "Broadcast to all" filter:
value: "all_accounts" integration: whatsapp_bridge_integration
# Dieser Teil sorgt dafür, dass HA die Namen deiner Accounts anzeigt domain: sensor
custom_value: true
message: message:
name: Message name: Message
description: The content of your WhatsApp message. description: The content of your message.
required: true required: true
selector: selector:
text: text:
multiline: true multiline: true
use_manual_number:
name: Use Manual Number
description: Enable this to ignore the recipient and use the number field below.
default: false
selector:
boolean:
number:
name: Manual Number
description: "Direct phone number (e.g., 491701234567)."
selector:
text: