from celery import Celery from celery.schedules import crontab from app.services.bot_service import BotService import os import json from datetime import datetime, timedelta from typing import List, Dict, Optional celery = Celery( 'tasks', broker=os.getenv("CELERY_BROKER_URL", "redis://localhost:6379/0"), backend=os.getenv("CELERY_RESULT_BACKEND", "redis://localhost:6379/0"), ) bot_service = BotService( os.getenv("TELEGRAM_BOT_TOKEN", ""), os.getenv("TELEGRAM_CHAT_ID", "") ) # Load schedules from JSON def load_schedules() -> List[Dict]: schedules_path = "/app/schedules.json" if os.path.exists(schedules_path): with open(schedules_path, "r") as f: return json.load(f) return [] # Save schedules to JSON def save_schedules(schedules: List[Dict]): with open("/app/schedules.json", "w") as f: json.dump(schedules, f, indent=2) @celery.task def send_scheduled_message(schedule_id: int): """Send scheduled message to Telegram.""" schedules = load_schedules() schedule = next((s for s in schedules if s['id'] == schedule_id), None) if not schedule: print(f"Schedule {schedule_id} not found") return if schedule.get('enabled', True): # Send to bot service try: bot_service.send_scheduled_message(schedule) print(f"Sent scheduled message: {schedule['time']}") except Exception as e: print(f"Error sending scheduled message: {e}") @celery.task def generate_daily_content(): """Generate daily content for all books.""" try: bot_service.generate_daily_content() print("Sent daily content") except Exception as e: print(f"Error generating daily content: {e}") # Periodic tasks celery.conf.beat_schedule = { 'send-scheduled-messages': { 'task': 'app.tasks.celery_tasks.send_scheduled_message', 'schedule': crontab(minute=0), # Every hour 'args': (None,), # Process all enabled schedules }, 'generate-daily-content': { 'task': 'app.tasks.celery_tasks.generate_daily_content', 'schedule': crontab(hour=8, minute=0), # Daily at 8 AM }, }