Files
biblioteca_conocimiento_lab…/vigilancia/notificador.py

74 lines
2.3 KiB
Python

import os
import subprocess
import requests
import config
def enviar_telegram(ruta_imagen: str, texto: str, chat_id=None):
chat_id = chat_id or config.TELEGRAM_CHAT_ID
if not config.TELEGRAM_TOKEN or not chat_id:
print("[Telegram] Falta TELEGRAM_TOKEN o chat_id")
return
url = f"https://api.telegram.org/bot{config.TELEGRAM_TOKEN}/sendPhoto"
try:
with open(ruta_imagen, "rb") as f:
r = requests.post(
url,
data={"chat_id": chat_id, "caption": texto},
files={"photo": f},
timeout=10,
)
if not r.ok:
print(f"[Telegram] Error {r.status_code}: {r.text[:200]}")
except Exception as e:
print(f"[Telegram] Excepción al enviar: {e}")
def enviar_texto_telegram(texto: str, chat_id=None):
chat_id = chat_id or config.TELEGRAM_CHAT_ID
if not config.TELEGRAM_TOKEN or not chat_id:
print("[Telegram] Falta TELEGRAM_TOKEN o chat_id")
return
url = f"https://api.telegram.org/bot{config.TELEGRAM_TOKEN}/sendMessage"
try:
r = requests.post(
url,
data={"chat_id": chat_id, "text": texto, "parse_mode": "HTML"},
timeout=10,
)
if not r.ok:
print(f"[Telegram] Error {r.status_code}: {r.text[:200]}")
except Exception as e:
print(f"[Telegram] Excepción al enviar: {e}")
def disparar_webhook_alexa(texto: str):
if config.ALEXA_NOTIFY_SCRIPT:
env = os.environ.copy()
if config.VOICEMONKEY_TOKEN:
env["VOICEMONKEY_TOKEN"] = config.VOICEMONKEY_TOKEN
if config.VOICEMONKEY_DEVICE:
env["VOICEMONKEY_DEVICE"] = config.VOICEMONKEY_DEVICE
try:
r = subprocess.run(
[config.ALEXA_NODE, config.ALEXA_NOTIFY_SCRIPT, texto],
env=env, timeout=15, capture_output=True, text=True,
)
if r.returncode != 0:
print(f"[Alexa] Error middleware: {r.stderr[:200]}")
except Exception as e:
print(f"[Alexa] Excepción lanzando middleware: {e}")
return
if not config.WEBHOOK_ALEXA:
return
try:
requests.post(config.WEBHOOK_ALEXA, json={"mensaje": texto}, timeout=5)
except Exception as e:
print(f"[Webhook Alexa] Excepción: {e}")