Files
social-media-automation/app/api/routes/notifications.py
Consultoría AS edc0e5577b feat(phase-4): Complete scheduling and automation system
- Add Celery worker with 5 scheduled tasks (Beat)
- Create ContentScheduler for optimal posting times
- Add calendar endpoints for scheduled posts management
- Implement Telegram notification service
- Add notification API with setup guide

Celery Beat Schedule:
- check_scheduled_posts: Every minute
- generate_daily_content: Daily at 6 AM
- sync_interactions: Every 15 minutes
- send_daily_summary: Daily at 9 PM
- cleanup_old_data: Weekly on Sundays

New endpoints:
- GET /api/calendar/posts/scheduled - List scheduled posts
- GET /api/calendar/posts/view - Calendar view
- GET /api/calendar/posts/slots - Available time slots
- POST /api/calendar/posts/{id}/schedule - Schedule post
- POST /api/calendar/posts/{id}/publish-now - Publish immediately
- GET /api/notifications/status - Check notification config
- POST /api/notifications/test - Send test notification
- GET /api/notifications/setup-guide - Configuration guide

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-28 01:56:10 +00:00

144 lines
4.3 KiB
Python

"""
API Routes for notification management.
"""
from fastapi import APIRouter, HTTPException
from pydantic import BaseModel
from typing import Optional
from app.core.config import settings
from app.services.notifications import telegram_notify, notification_service
router = APIRouter()
class TestNotificationRequest(BaseModel):
"""Request for testing notifications."""
message: Optional[str] = "Test desde Social Media Automation"
class NotificationSettingsResponse(BaseModel):
"""Response with notification settings."""
telegram_configured: bool
bot_token_set: bool
chat_id_set: bool
@router.get("/status")
async def get_notification_status():
"""
Verificar estado de las notificaciones.
Muestra si Telegram está configurado correctamente.
"""
return NotificationSettingsResponse(
telegram_configured=notification_service.telegram_enabled,
bot_token_set=bool(settings.TELEGRAM_BOT_TOKEN),
chat_id_set=bool(settings.TELEGRAM_CHAT_ID)
)
@router.post("/test")
async def test_notification(request: TestNotificationRequest):
"""
Enviar notificación de prueba.
Útil para verificar que la configuración de Telegram funciona.
"""
if not notification_service.telegram_enabled:
raise HTTPException(
status_code=503,
detail="Telegram no configurado. Agrega TELEGRAM_BOT_TOKEN y TELEGRAM_CHAT_ID en .env"
)
message = f"🧪 *Test de Notificación*\n\n{request.message}\n\n✅ Si ves esto, las notificaciones funcionan correctamente."
success = await telegram_notify(message)
if success:
return {"success": True, "message": "Notificación enviada"}
else:
raise HTTPException(
status_code=500,
detail="Error al enviar notificación. Verifica las credenciales."
)
@router.post("/send")
async def send_custom_notification(
message: str,
parse_mode: str = "Markdown"
):
"""
Enviar notificación personalizada.
- **message**: Texto del mensaje (soporta Markdown)
- **parse_mode**: "Markdown" o "HTML"
"""
if not notification_service.telegram_enabled:
raise HTTPException(
status_code=503,
detail="Telegram no configurado"
)
success = await telegram_notify(message, parse_mode)
return {"success": success}
@router.get("/setup-guide")
async def get_setup_guide():
"""
Obtener guía de configuración de Telegram.
"""
return {
"title": "Configuración de Notificaciones Telegram",
"steps": [
{
"step": 1,
"title": "Crear Bot de Telegram",
"instructions": [
"Abre Telegram y busca @BotFather",
"Envía el comando /newbot",
"Sigue las instrucciones para nombrar tu bot",
"Guarda el token que te proporciona"
]
},
{
"step": 2,
"title": "Obtener Chat ID",
"instructions": [
"Inicia una conversación con tu nuevo bot",
"Envía cualquier mensaje",
"Visita: https://api.telegram.org/bot<TU_TOKEN>/getUpdates",
"Busca el campo 'chat': {'id': XXXXXXX}",
"Ese número es tu CHAT_ID"
]
},
{
"step": 3,
"title": "Configurar Variables",
"instructions": [
"Edita tu archivo .env",
"Agrega: TELEGRAM_BOT_TOKEN=tu_token_aqui",
"Agrega: TELEGRAM_CHAT_ID=tu_chat_id_aqui",
"Reinicia la aplicación"
]
},
{
"step": 4,
"title": "Verificar",
"instructions": [
"Usa el endpoint POST /api/notifications/test",
"Deberías recibir un mensaje en Telegram"
]
}
],
"current_status": {
"configured": notification_service.telegram_enabled,
"bot_token": "✓ Configurado" if settings.TELEGRAM_BOT_TOKEN else "✗ Falta",
"chat_id": "✓ Configurado" if settings.TELEGRAM_CHAT_ID else "✗ Falta"
}
}