Files
Whatsapp-Bridge-Integration/custom_components/whatsapp_bridge_integration/__init__.py

50 lines
1.8 KiB
Python

import logging
import requests
from homeassistant.core import HomeAssistant, ServiceCall
from .const import DOMAIN, CONF_PHONE_NUMBER, CONF_ACCOUNT_NAME
_LOGGER = logging.getLogger(__name__)
async def async_setup_entry(hass: HomeAssistant, entry):
"""Set up a profile from a config entry."""
if not hass.services.has_service(DOMAIN, "send_message"):
async def handle_send_message(call: ServiceCall):
message = call.data.get("message")
target_account = call.data.get("account")
target_number = call.data.get("number")
all_accounts = call.data.get("all_accounts", False)
entries = hass.config_entries.async_entries(DOMAIN)
targets = []
if all_accounts:
for e in entries:
targets.append(e.data.get(CONF_PHONE_NUMBER))
elif target_number:
targets.append(target_number)
elif target_account:
for e in entries:
if e.title.lower() == target_account.lower():
targets.append(e.data.get(CONF_PHONE_NUMBER))
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 sent to %s", num)
except Exception as e:
_LOGGER.error("Failed to send to %s: %s", num, str(e))
hass.services.async_register(DOMAIN, "send_message", handle_send_message)
return True
async def async_unload_entry(hass, entry):
return True