Files
hackathon-innovaflow5.0-cdf…/backend/app/services/notifications.py

72 lines
2.8 KiB
Python

import os
import firebase_admin
import urllib.parse
import urllib.request
from firebase_admin import credentials, messaging
_firebase_initialized = False
def init_firebase(cred_path: str):
"""Inicializa la conexión con Firebase usando el Service Account (JSON)."""
global _firebase_initialized
if os.path.exists(cred_path):
try:
cred = credentials.Certificate(cred_path)
firebase_admin.initialize_app(cred)
_firebase_initialized = True
print(f"Firebase Admin SDK inicializado correctamente desde: {cred_path}")
except ValueError:
# Si el entorno se recarga, Firebase podría quejarse de que ya se inicializó
_firebase_initialized = True
except Exception as e:
print(f"Error al inicializar Firebase: {e}")
else:
print(f"ADVERTENCIA: Credenciales no encontradas en '{cred_path}'.")
print("Las notificaciones se ejecutarán en modo SIMULADO (solo consola).")
def send_to_topic(topic: str, payload: dict):
"""Envía una notificación push a todos los dispositivos suscritos a un topic (ej. RUTA-01)."""
title = payload.get("title", "")
body = payload.get("body", "")
# `data` viaja como Dict[str, str] en FCM; permite que el cliente
# clasifique el evento (event, routeId) en notifications_screen.dart.
raw_data = payload.get("data") or {}
data: dict[str, str] = {str(k): str(v) for k, v in raw_data.items() if v is not None}
if not _firebase_initialized:
print(f"[MOCK PUSH] -> Topic: {topic} | Título: '{title}' | Mensaje: '{body}' | Data: {data}")
return
try:
message = messaging.Message(
notification=messaging.Notification(
title=title,
body=body,
),
data=data or None,
topic=topic,
)
response = messaging.send(message)
print(f"Push enviado al topic '{topic}' exitosamente. MessageID: {response}")
except Exception as e:
print(f"Error al enviar push al topic '{topic}': {e}")
def send_whatsapp_alert(phone: str, message: str):
"""
Envía un WhatsApp usando la API gratuita de CallMeBot.
"""
print("\n" + "="*50)
print(f"🟢 [WHATSAPP TRIGGER] Preparando mensaje para {phone}")
print(f"💬 Mensaje: {message}")
print("="*50 + "\n")
# REEMPLAZA ESTO POR EL CÓDIGO QUE TE DIO EL BOT EN WHATSAPP:
apikey = "6756808" # <--- BORRA "TU_API_KEY_AQUI" Y PON TU CÓDIGO REAL AQUÍ
safe_msg = urllib.parse.quote(message)
url = f"https://api.callmebot.com/whatsapp.php?phone={phone}&text={safe_msg}&apikey={apikey}"
try:
urllib.request.urlopen(url, timeout=5)
except Exception as e:
print(f"Error enviando WhatsApp real: {e}")