import json import os import logging logger = logging.getLogger(__name__) CONFIG_FILE = "data/bot_config.json" # Default hardcoded configuration (Seed values) DEFAULT_CHANNELS = { "jee_main": { "id": "@JEE_NEET_Handwritten_Note", "label": "JEE Main Daily", "exam_focus": ["JEE Main"], "subjects": ["physics", "chemistry", "maths"], "active": True, "mcq_poll_enabled": True, "mcq_poll_delay_min": 60, "mcq_poll_delay_max": 90, # This channel ONLY runs the 10-MCQ Poll Session at 8 PM "disabled_content_types": ["pyq_question", "formula_sheet", "short_notes", "mnemonic", "concept_recap", "mock_question", "motivational"], "footer": "šŸŽÆ *Crack JEE Main 2025!*\nšŸ“¢ Share with your batch!", "button_text": "", "button_url": "", "hashtags": { "pyq": "#JEEMain #PYQ #JEEPrep", "formula": "#JEEFormula #JEEMaths #JEEPhysics", "notes": "#JEENotes #QuickRevision", "mnemonic": "#MemoryTrick #JEETricks", "mock": "#JEEMock #PracticeNow", "recap": "#JEERecap #ConceptClear", }, }, "neet": { "id": "@NEET_HandwrittenNotes_2026", "label": "NEET Daily", "exam_focus": ["NEET"], "subjects": ["physics", "chemistry", "biology"], "active": True, "mcq_poll_enabled": False, "mcq_poll_delay_min": 60, "mcq_poll_delay_max": 90, "disabled_content_types": ["pyq_question"], # No quiz polls on this channel "footer": "šŸ„ *Future Doctors — Keep Going!*\nšŸ“¢ Share with your study group!", "button_text": "", "button_url": "", "hashtags": { "pyq": "#NEET #NEETPapers #BiologyPYQ", "formula": "#NEETFormula #BiologyFacts", "notes": "#NEETNotes #MedicalPrep", "mnemonic": "#BioMnemonic #NEETTricks", "mock": "#NEETMock #Practice", "recap": "#NEETRecap #BioRevision", }, }, "jee_advanced": { "id": "@JEE_ADVANCED_NOTES_2026", "label": "JEE Advanced Daily", "exam_focus": ["JEE Advanced"], "subjects": ["physics", "chemistry", "maths"], "active": True, "mcq_poll_enabled": False, "mcq_poll_delay_min": 60, "mcq_poll_delay_max": 90, "disabled_content_types": ["pyq_question"], # No quiz polls on this channel "footer": "šŸ”„ *IIT Aspirant — You've got this!*\nšŸ“¢ Forward to your IIT group!", "button_text": "", "button_url": "", "hashtags": { "pyq": "#JEEAdvanced #IIT #HardProblems", "formula": "#AdvancedFormula #IITLevel", "notes": "#IITNotes #AdvancedConcepts", "mnemonic": "#SmartStudy #IITTricks", "mock": "#AdvancedMock #IITLevel", "recap": "#IITRecap #DeepConcepts", }, } } DEFAULT_SCHEDULE = { "pyq_question": {"hour": 7, "minute": 0}, "formula_sheet": {"hour": 9, "minute": 0}, "short_notes": {"hour": 12, "minute": 0}, "mnemonic": {"hour": 15, "minute": 0}, "concept_recap": {"hour": 18, "minute": 0}, "mock_question": {"hour": 20, "minute": 0}, "motivational": {"hour": 22, "minute": 0}, # MCQ Poll Session — runs INDEPENDENTLY (not via normal post_content loop) # hour/minute = when the session STARTS; polls trickle every 60-90s after "mcq_session": {"hour": 20, "minute": 0}, } DEFAULT_SETTINGS = { "main_channel_name": "NEET Notes", "main_channel_url": "https://t.me/NEET_HandwrittenNotes_2026", "dashboard_url": "https://huggingface.co/spaces/H3y-sam/TELEGRAM-BOT/", "bot_name": "JEE & NEET Assistant" } class ConfigManager: def __init__(self): self.channels = DEFAULT_CHANNELS self.schedule = DEFAULT_SCHEDULE self.settings = DEFAULT_SETTINGS self.load() def load(self): """Load configuration from Gist (remote) or JSON file (local).""" # 1. Try to pull from Gist first (remote persistence) from content.remote_storage import pull_from_gist remote_data = pull_from_gist(os.path.basename(CONFIG_FILE)) if remote_data: if "channels" in remote_data: self.channels = remote_data["channels"] if "schedule" in remote_data: self.schedule = remote_data["schedule"] if "settings" in remote_data: self.settings.update(remote_data["settings"]) logger.info(f"[OK] Config loaded from Gist") # Save locally to stay in sync self._save_local() return # 2. Fallback to local file if os.path.exists(CONFIG_FILE): try: with open(CONFIG_FILE, "r") as f: data = json.load(f) if "channels" in data: self.channels = data["channels"] if "schedule" in data: self.schedule = data["schedule"] if "settings" in data: self.settings.update(data["settings"]) logger.info(f"[OK] Dynamic config loaded from {CONFIG_FILE}") except Exception as e: logger.error(f"[ERROR] Failed to load dynamic config: {e}. Using defaults.") def _save_local(self): """Internal helper to save config to local file.""" try: os.makedirs(os.path.dirname(CONFIG_FILE), exist_ok=True) temp_file = CONFIG_FILE + ".tmp" with open(temp_file, "w") as f: json.dump({ "channels": self.channels, "schedule": self.schedule, "settings": self.settings }, f, indent=4) os.replace(temp_file, CONFIG_FILE) except Exception as e: logger.error(f"[LOCAL SAVE ERROR] {e}") def save(self): """Save current configuration to local file AND GitHub Gist.""" # 1. Save locally self._save_local() logger.info(f"[OK] Dynamic config saved locally to {CONFIG_FILE}") # 2. Push to Gist from content.remote_storage import push_to_gist push_to_gist(os.path.basename(CONFIG_FILE), { "channels": self.channels, "schedule": self.schedule, "settings": self.settings }) def add_channel(self, key: str, channel_id: str, label: str, exam_focus: list = None, subjects: list = None, mcq_only: bool = False) -> bool: """Add a new channel. Returns False if key already exists.""" if key in self.channels: return False disabled = ["pyq_question", "formula_sheet", "short_notes", "mnemonic", "concept_recap", "mock_question", "motivational"] if mcq_only else [] self.channels[key] = { "id": channel_id, "label": label, "exam_focus": exam_focus or ["JEE Main"], "subjects": subjects or ["physics", "chemistry", "maths"], "active": True, "mcq_poll_enabled": mcq_only, "mcq_poll_delay_min": 60, "mcq_poll_delay_max": 90, "disabled_content_types": disabled, "footer": "šŸ“¢ Share with your batch!\nšŸ”— @xcrazylearners", "button_text": "", "button_url": "", "hashtags": { "pyq": "#JEEMain #PYQ", "formula": "#Formula #Notes", "notes": "#Notes #Revision", "mnemonic": "#MemoryTrick", "mock": "#Mock #Practice", "recap": "#Recap #Concept", } } self.save() return True def delete_channel(self, key: str) -> bool: """Remove a channel from configuration.""" if key not in self.channels: return False del self.channels[key] self.save() return True def update_channel(self, key: str, updates: dict) -> bool: """Patch specific fields of a channel config.""" if key not in self.channels: return False self.channels[key].update(updates) self.save() return True def set_schedule(self, content_type: str, hour: int, minute: int) -> bool: """Update posting time for a content type.""" if content_type not in self.schedule: return False self.schedule[content_type] = {"hour": int(hour), "minute": int(minute)} self.save() return True def add_content_type(self, type_key, hour, minute): if type_key in self.schedule: return False self.schedule[type_key] = {"hour": int(hour), "minute": int(minute)} self.save() return True def delete_content_type(self, type_key): if type_key in self.schedule: del self.schedule[type_key] # Also remove from all channel disabled lists to be clean for ch in self.channels.values(): if type_key in ch.get("disabled_content_types", []): ch["disabled_content_types"].remove(type_key) self.save() return True return False def toggle_channel(self, key): if key in self.channels: self.channels[key]["active"] = not self.channels[key]["active"] self.save() return self.channels[key]["active"] return None def toggle_content_type(self, channel_key: str, content_type: str) -> bool: if channel_key not in self.channels: return False disabled = self.channels[channel_key].setdefault("disabled_content_types", []) if content_type in disabled: disabled.remove(content_type) enabled = True else: disabled.append(content_type) enabled = False self.channels[channel_key]["disabled_content_types"] = disabled self.save() return enabled def is_content_type_enabled(self, channel_key: str, content_type: str) -> bool: disabled = self.channels.get(channel_key, {}).get("disabled_content_types", []) return content_type not in disabled def toggle_mcq_poll(self, key): if key in self.channels: current = self.channels[key].get("mcq_poll_enabled", False) self.channels[key]["mcq_poll_enabled"] = not current self.save() return self.channels[key]["mcq_poll_enabled"] return None def set_mcq_delay(self, key, delay_min: int, delay_max: int): if key in self.channels: self.channels[key]["mcq_poll_delay_min"] = int(delay_min) self.channels[key]["mcq_poll_delay_max"] = int(delay_max) self.save() return True return False def update_time(self, content_type, hour, minute): return self.set_schedule(content_type, hour, minute) def update_settings(self, updates: dict): self.settings.update(updates) self.save() return True # Singleton instance config_manager = ConfigManager()