Implementación inicial del sistema de automatización de redes sociales
- Estructura completa del proyecto con FastAPI - Modelos de base de datos (productos, servicios, posts, calendario, interacciones) - Publishers para X, Threads, Instagram, Facebook - Generador de contenido con DeepSeek API - Worker de Celery con tareas programadas - Dashboard básico con templates HTML - Docker Compose para despliegue - Documentación completa Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
This commit is contained in:
123
worker/tasks/fetch_interactions.py
Normal file
123
worker/tasks/fetch_interactions.py
Normal file
@@ -0,0 +1,123 @@
|
||||
"""
|
||||
Tareas para obtener interacciones de redes sociales.
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
from datetime import datetime
|
||||
|
||||
from worker.celery_app import celery_app
|
||||
from app.core.database import SessionLocal
|
||||
from app.models.interaction import Interaction
|
||||
from app.models.post import Post
|
||||
from app.publishers import get_publisher
|
||||
|
||||
|
||||
def run_async(coro):
|
||||
"""Helper para ejecutar coroutines en Celery."""
|
||||
loop = asyncio.get_event_loop()
|
||||
return loop.run_until_complete(coro)
|
||||
|
||||
|
||||
@celery_app.task(name="worker.tasks.fetch_interactions.fetch_all_interactions")
|
||||
def fetch_all_interactions():
|
||||
"""
|
||||
Obtener interacciones de todas las plataformas.
|
||||
Se ejecuta cada 5 minutos.
|
||||
"""
|
||||
platforms = ["x", "threads", "instagram", "facebook"]
|
||||
results = []
|
||||
|
||||
for platform in platforms:
|
||||
try:
|
||||
result = fetch_platform_interactions.delay(platform)
|
||||
results.append(f"{platform}: tarea enviada")
|
||||
except Exception as e:
|
||||
results.append(f"{platform}: error - {e}")
|
||||
|
||||
return results
|
||||
|
||||
|
||||
@celery_app.task(name="worker.tasks.fetch_interactions.fetch_platform_interactions")
|
||||
def fetch_platform_interactions(platform: str):
|
||||
"""Obtener interacciones de una plataforma específica."""
|
||||
db = SessionLocal()
|
||||
|
||||
try:
|
||||
publisher = get_publisher(platform)
|
||||
|
||||
# Obtener menciones
|
||||
mentions = run_async(publisher.get_mentions())
|
||||
new_mentions = 0
|
||||
|
||||
for mention in mentions:
|
||||
external_id = mention.get("id")
|
||||
|
||||
# Verificar si ya existe
|
||||
existing = db.query(Interaction).filter(
|
||||
Interaction.external_id == external_id
|
||||
).first()
|
||||
|
||||
if not existing:
|
||||
interaction = Interaction(
|
||||
platform=platform,
|
||||
interaction_type="mention",
|
||||
external_id=external_id,
|
||||
author_username=mention.get("username", mention.get("author_id", "unknown")),
|
||||
author_name=mention.get("name"),
|
||||
content=mention.get("text", mention.get("message")),
|
||||
interaction_at=datetime.fromisoformat(
|
||||
mention.get("created_at", datetime.utcnow().isoformat()).replace("Z", "+00:00")
|
||||
) if mention.get("created_at") else datetime.utcnow()
|
||||
)
|
||||
db.add(interaction)
|
||||
new_mentions += 1
|
||||
|
||||
# Obtener comentarios de posts recientes
|
||||
recent_posts = db.query(Post).filter(
|
||||
Post.platform_post_ids.isnot(None),
|
||||
Post.platforms.contains([platform])
|
||||
).order_by(Post.published_at.desc()).limit(10).all()
|
||||
|
||||
new_comments = 0
|
||||
|
||||
for post in recent_posts:
|
||||
platform_id = post.platform_post_ids.get(platform)
|
||||
if not platform_id:
|
||||
continue
|
||||
|
||||
comments = run_async(publisher.get_comments(platform_id))
|
||||
|
||||
for comment in comments:
|
||||
external_id = comment.get("id")
|
||||
|
||||
existing = db.query(Interaction).filter(
|
||||
Interaction.external_id == external_id
|
||||
).first()
|
||||
|
||||
if not existing:
|
||||
interaction = Interaction(
|
||||
platform=platform,
|
||||
interaction_type="comment",
|
||||
post_id=post.id,
|
||||
external_id=external_id,
|
||||
external_post_id=platform_id,
|
||||
author_username=comment.get("username", comment.get("from", {}).get("id", "unknown")),
|
||||
author_name=comment.get("from", {}).get("name") if isinstance(comment.get("from"), dict) else None,
|
||||
content=comment.get("text", comment.get("message")),
|
||||
interaction_at=datetime.fromisoformat(
|
||||
comment.get("created_at", comment.get("timestamp", comment.get("created_time", datetime.utcnow().isoformat()))).replace("Z", "+00:00")
|
||||
) if comment.get("created_at") or comment.get("timestamp") or comment.get("created_time") else datetime.utcnow()
|
||||
)
|
||||
db.add(interaction)
|
||||
new_comments += 1
|
||||
|
||||
db.commit()
|
||||
|
||||
return f"{platform}: {new_mentions} menciones, {new_comments} comentarios nuevos"
|
||||
|
||||
except Exception as e:
|
||||
db.rollback()
|
||||
return f"{platform}: error - {e}"
|
||||
|
||||
finally:
|
||||
db.close()
|
||||
Reference in New Issue
Block a user