H3y-sam commited on
Commit
94b42f2
Β·
verified Β·
1 Parent(s): f2decac

Upload 54 files

Browse files
bot.py CHANGED
@@ -264,7 +264,7 @@ class BotHandler(BaseHTTPRequestHandler):
264
  for ch_key, ch_cfg in channels.items():
265
  if ch_cfg.get("active") and _bot_loop and _bot_app:
266
  asyncio.run_coroutine_threadsafe(
267
- _bot_app.bot.send_message(ch_cfg["id"], msg, parse_mode="MarkdownV2"),
268
  _bot_loop
269
  )
270
  ok_count += 1
 
264
  for ch_key, ch_cfg in channels.items():
265
  if ch_cfg.get("active") and _bot_loop and _bot_app:
266
  asyncio.run_coroutine_threadsafe(
267
+ _bot_app.bot.send_message(ch_cfg["id"], msg, parse_mode="HTML"),
268
  _bot_loop
269
  )
270
  ok_count += 1
config.py CHANGED
@@ -1,55 +1,55 @@
1
- import os
2
- from dotenv import load_dotenv
3
-
4
- load_dotenv()
5
-
6
- # ─────────────────────────────────────────────
7
- # REQUIRED - Loads from .env file
8
- # ─────────────────────────────────────────────
9
-
10
- BOT_TOKEN = os.getenv("BOT_TOKEN", "") # From @BotFather
11
- GROQ_API_KEY = os.getenv("GROQ_API_KEY", "") # From console.groq.com
12
- GIST_ID = os.getenv("GIST_ID", "") # GitHub Gist ID
13
- GIST_TOKEN = os.getenv("GIST_TOKEN", "") # GitHub Personal Access Token
14
- GEMINI_API_KEY = os.getenv("GEMINI_API_KEY", "")
15
-
16
- # Parse comma-separated list of IDs from .env
17
- _admin_ids_raw = os.getenv("ADMIN_USER_IDS", "123456789")
18
- ADMIN_USER_IDS = [int(uid.strip()) for uid in _admin_ids_raw.split(",") if uid.strip().isdigit()]
19
-
20
- # ─────────────────────────────────────────────
21
- # REPEAT PREVENTION
22
- # ─────────────────────────────────────────────
23
- HISTORY_DEPTH = 60
24
- HISTORY_FILE = "data/content_history.json"
25
- HISTORY_FILE_NAME = "content_history.json"
26
-
27
- # ─────────────────────────────────────────────
28
- # DYNAMIC CONFIGURATION (IMPORT INSTANCE DIRECTLY)
29
- # ─────────────────────────────────────────────
30
- from content.config_manager import config_manager
31
- from content.syllabus_manager import syllabus_manager
32
-
33
- # ─────────────────────────────────────────────
34
- # SUBJECTS & CHAPTER POOL
35
- # ─────────────────────────────────────────────
36
-
37
- # The SUBJECTS dictionary is now handled dynamically by SyllabusManager via data/syllabus.json.
38
-
39
- SUBJECT_ROTATION = {
40
- "Monday": ["physics", "maths"],
41
- "Tuesday": ["chemistry", "biology"],
42
- "Wednesday": ["physics", "chemistry"],
43
- "Thursday": ["maths", "biology"],
44
- "Friday": ["physics", "chemistry", "maths"],
45
- "Saturday": ["biology", "chemistry"],
46
- "Sunday": ["physics", "maths", "biology"],
47
- }
48
-
49
- # ─────────────────────────────────────────────
50
- # GEMINI SETTINGS
51
- # ─────────────────────────────────────────────
52
-
53
- GEMINI_MODEL = "gemini-2.0-flash"
54
- GEMINI_MAX_TOKENS = 4500 # Sufficient for large MCQ sessions with detailed explanations
55
- GEMINI_TEMPERATURE = 0.7
 
1
+ import os
2
+ from dotenv import load_dotenv
3
+
4
+ load_dotenv()
5
+
6
+ # ─────────────────────────────────────────────
7
+ # REQUIRED - Loads from .env file
8
+ # ─────────────────────────────────────────────
9
+
10
+ BOT_TOKEN = os.getenv("BOT_TOKEN", "") # From @BotFather
11
+ GROQ_API_KEY = os.getenv("GROQ_API_KEY", "") # From console.groq.com
12
+ GIST_ID = os.getenv("GIST_ID", "") # GitHub Gist ID
13
+ GIST_TOKEN = os.getenv("GIST_TOKEN", "") # GitHub Personal Access Token
14
+ GEMINI_API_KEY = os.getenv("GEMINI_API_KEY", "")
15
+
16
+ # Parse comma-separated list of IDs from .env
17
+ _admin_ids_raw = os.getenv("ADMIN_USER_IDS", "123456789")
18
+ ADMIN_USER_IDS = [int(uid.strip()) for uid in _admin_ids_raw.split(",") if uid.strip().isdigit()]
19
+
20
+ # ─────────────────────────────────────────────
21
+ # REPEAT PREVENTION
22
+ # ─────────────────────────────────────────────
23
+ HISTORY_DEPTH = 60
24
+ HISTORY_FILE = "data/content_history.json"
25
+ HISTORY_FILE_NAME = "content_history.json"
26
+
27
+ # ─────────────────────────────────────────────
28
+ # DYNAMIC CONFIGURATION (IMPORT INSTANCE DIRECTLY)
29
+ # ─────────────────────────────────────────────
30
+ from content.config_manager import config_manager
31
+ from content.syllabus_manager import syllabus_manager
32
+
33
+ # ─────────────────────────────────────────────
34
+ # SUBJECTS & CHAPTER POOL
35
+ # ─────────────────────────────────────────────
36
+
37
+ # The SUBJECTS dictionary is now handled dynamically by SyllabusManager via data/syllabus.json.
38
+
39
+ SUBJECT_ROTATION = {
40
+ "Monday": ["physics", "maths"],
41
+ "Tuesday": ["chemistry", "biology"],
42
+ "Wednesday": ["physics", "chemistry"],
43
+ "Thursday": ["maths", "biology"],
44
+ "Friday": ["physics", "chemistry", "maths"],
45
+ "Saturday": ["biology", "chemistry"],
46
+ "Sunday": ["physics", "maths", "biology"],
47
+ }
48
+
49
+ # ─────────────────────────────────────────────
50
+ # GEMINI SETTINGS
51
+ # ─────────────────────────────────────────────
52
+
53
+ GEMINI_MODEL = "gemini-2.0-flash"
54
+ GEMINI_MAX_TOKENS = 4500 # Sufficient for large MCQ sessions with detailed explanations
55
+ GEMINI_TEMPERATURE = 0.7
content/config_manager.py CHANGED
@@ -1,288 +1,288 @@
1
- import json
2
- import os
3
- import logging
4
-
5
- logger = logging.getLogger(__name__)
6
-
7
- CONFIG_FILE = "data/bot_config.json"
8
-
9
- # Default hardcoded configuration (Seed values)
10
- DEFAULT_CHANNELS = {
11
- "jee_main": {
12
- "id": "@JEE_NEET_Handwritten_Note",
13
- "label": "JEE Main Daily",
14
- "exam_focus": ["JEE Main"],
15
- "subjects": ["physics", "chemistry", "maths"],
16
- "active": True,
17
- "mcq_poll_enabled": True,
18
- "mcq_poll_delay_min": 60,
19
- "mcq_poll_delay_max": 90,
20
- # This channel ONLY runs the 10-MCQ Poll Session at 8 PM
21
- "disabled_content_types": ["pyq_question", "formula_sheet", "short_notes",
22
- "mnemonic", "concept_recap", "mock_question", "motivational"],
23
- "footer": "🎯 *Crack JEE Main 2025!*\nπŸ“’ Share with your batch!",
24
- "button_text": "",
25
- "button_url": "",
26
- "hashtags": {
27
- "pyq": "#JEEMain #PYQ #JEEPrep",
28
- "formula": "#JEEFormula #JEEMaths #JEEPhysics",
29
- "notes": "#JEENotes #QuickRevision",
30
- "mnemonic": "#MemoryTrick #JEETricks",
31
- "mock": "#JEEMock #PracticeNow",
32
- "recap": "#JEERecap #ConceptClear",
33
- },
34
- },
35
- "neet": {
36
- "id": "@NEET_HandwrittenNotes_2026",
37
- "label": "NEET Daily",
38
- "exam_focus": ["NEET"],
39
- "subjects": ["physics", "chemistry", "biology"],
40
- "active": True,
41
- "mcq_poll_enabled": False,
42
- "mcq_poll_delay_min": 60,
43
- "mcq_poll_delay_max": 90,
44
- "disabled_content_types": ["pyq_question"], # No quiz polls on this channel
45
- "footer": "πŸ₯ *Future Doctors β€” Keep Going!*\nπŸ“’ Share with your study group!",
46
- "button_text": "",
47
- "button_url": "",
48
- "hashtags": {
49
- "pyq": "#NEET #NEETPapers #BiologyPYQ",
50
- "formula": "#NEETFormula #BiologyFacts",
51
- "notes": "#NEETNotes #MedicalPrep",
52
- "mnemonic": "#BioMnemonic #NEETTricks",
53
- "mock": "#NEETMock #Practice",
54
- "recap": "#NEETRecap #BioRevision",
55
- },
56
- },
57
- "jee_advanced": {
58
- "id": "@JEE_ADVANCED_NOTES_2026",
59
- "label": "JEE Advanced Daily",
60
- "exam_focus": ["JEE Advanced"],
61
- "subjects": ["physics", "chemistry", "maths"],
62
- "active": True,
63
- "mcq_poll_enabled": False,
64
- "mcq_poll_delay_min": 60,
65
- "mcq_poll_delay_max": 90,
66
- "disabled_content_types": ["pyq_question"], # No quiz polls on this channel
67
- "footer": "πŸ”₯ *IIT Aspirant β€” You've got this!*\nπŸ“’ Forward to your IIT group!",
68
- "button_text": "",
69
- "button_url": "",
70
- "hashtags": {
71
- "pyq": "#JEEAdvanced #IIT #HardProblems",
72
- "formula": "#AdvancedFormula #IITLevel",
73
- "notes": "#IITNotes #AdvancedConcepts",
74
- "mnemonic": "#SmartStudy #IITTricks",
75
- "mock": "#AdvancedMock #IITLevel",
76
- "recap": "#IITRecap #DeepConcepts",
77
- },
78
- }
79
- }
80
-
81
- DEFAULT_SCHEDULE = {
82
- "pyq_question": {"hour": 7, "minute": 0},
83
- "formula_sheet": {"hour": 9, "minute": 0},
84
- "short_notes": {"hour": 12, "minute": 0},
85
- "mnemonic": {"hour": 15, "minute": 0},
86
- "concept_recap": {"hour": 18, "minute": 0},
87
- "mock_question": {"hour": 20, "minute": 0},
88
- "motivational": {"hour": 22, "minute": 0},
89
- # MCQ Poll Session β€” runs INDEPENDENTLY (not via normal post_content loop)
90
- # hour/minute = when the session STARTS; polls trickle every 60-90s after
91
- "mcq_session": {"hour": 20, "minute": 0},
92
- }
93
-
94
- DEFAULT_SETTINGS = {
95
- "main_channel_name": "NEET Notes",
96
- "main_channel_url": "https://t.me/NEET_HandwrittenNotes_2026",
97
- "dashboard_url": "https://huggingface.co/spaces/H3y-sam/TELEGRAM-BOT/",
98
- "bot_name": "JEE & NEET Assistant"
99
- }
100
-
101
- class ConfigManager:
102
- def __init__(self):
103
- self.channels = DEFAULT_CHANNELS
104
- self.schedule = DEFAULT_SCHEDULE
105
- self.settings = DEFAULT_SETTINGS
106
- self.load()
107
-
108
- def load(self):
109
- """Load configuration from Gist (remote) or JSON file (local)."""
110
- # 1. Try to pull from Gist first (remote persistence)
111
- from content.remote_storage import pull_from_gist
112
- remote_data = pull_from_gist(os.path.basename(CONFIG_FILE))
113
- if remote_data:
114
- if "channels" in remote_data: self.channels = remote_data["channels"]
115
- if "schedule" in remote_data: self.schedule = remote_data["schedule"]
116
- if "settings" in remote_data: self.settings.update(remote_data["settings"])
117
- logger.info(f"[OK] Config loaded from Gist")
118
- # Save locally to stay in sync
119
- self._save_local()
120
- return
121
-
122
- # 2. Fallback to local file
123
- if os.path.exists(CONFIG_FILE):
124
- try:
125
- with open(CONFIG_FILE, "r") as f:
126
- data = json.load(f)
127
- if "channels" in data: self.channels = data["channels"]
128
- if "schedule" in data: self.schedule = data["schedule"]
129
- if "settings" in data: self.settings.update(data["settings"])
130
- logger.info(f"[OK] Dynamic config loaded from {CONFIG_FILE}")
131
- except Exception as e:
132
- logger.error(f"[ERROR] Failed to load dynamic config: {e}. Using defaults.")
133
-
134
- def _save_local(self):
135
- """Internal helper to save config to local file."""
136
- try:
137
- os.makedirs(os.path.dirname(CONFIG_FILE), exist_ok=True)
138
- temp_file = CONFIG_FILE + ".tmp"
139
- with open(temp_file, "w") as f:
140
- json.dump({
141
- "channels": self.channels,
142
- "schedule": self.schedule,
143
- "settings": self.settings
144
- }, f, indent=4)
145
- os.replace(temp_file, CONFIG_FILE)
146
- except Exception as e:
147
- logger.error(f"[LOCAL SAVE ERROR] {e}")
148
-
149
- def save(self):
150
- """Save current configuration to local file AND GitHub Gist."""
151
- # 1. Save locally
152
- self._save_local()
153
- logger.info(f"[OK] Dynamic config saved locally to {CONFIG_FILE}")
154
-
155
- # 2. Push to Gist
156
- from content.remote_storage import push_to_gist
157
- push_to_gist(os.path.basename(CONFIG_FILE), {
158
- "channels": self.channels,
159
- "schedule": self.schedule,
160
- "settings": self.settings
161
- })
162
-
163
- def add_channel(self, key: str, channel_id: str, label: str,
164
- exam_focus: list = None, subjects: list = None,
165
- mcq_only: bool = False) -> bool:
166
- """Add a new channel. Returns False if key already exists."""
167
- if key in self.channels:
168
- return False
169
- disabled = ["pyq_question", "formula_sheet", "short_notes",
170
- "mnemonic", "concept_recap", "mock_question", "motivational"] if mcq_only else []
171
- self.channels[key] = {
172
- "id": channel_id,
173
- "label": label,
174
- "exam_focus": exam_focus or ["JEE Main"],
175
- "subjects": subjects or ["physics", "chemistry", "maths"],
176
- "active": True,
177
- "mcq_poll_enabled": mcq_only,
178
- "mcq_poll_delay_min": 60,
179
- "mcq_poll_delay_max": 90,
180
- "disabled_content_types": disabled,
181
- "footer": "πŸ“’ Share with your batch!\nπŸ”— @xcrazylearners",
182
- "button_text": "",
183
- "button_url": "",
184
- "hashtags": {
185
- "pyq": "#JEEMain #PYQ",
186
- "formula": "#Formula #Notes",
187
- "notes": "#Notes #Revision",
188
- "mnemonic": "#MemoryTrick",
189
- "mock": "#Mock #Practice",
190
- "recap": "#Recap #Concept",
191
- }
192
- }
193
- self.save()
194
- return True
195
-
196
- def delete_channel(self, key: str) -> bool:
197
- """Remove a channel from configuration."""
198
- if key not in self.channels:
199
- return False
200
- del self.channels[key]
201
- self.save()
202
- return True
203
-
204
- def update_channel(self, key: str, updates: dict) -> bool:
205
- """Patch specific fields of a channel config."""
206
- if key not in self.channels:
207
- return False
208
- self.channels[key].update(updates)
209
- self.save()
210
- return True
211
-
212
- def set_schedule(self, content_type: str, hour: int, minute: int) -> bool:
213
- """Update posting time for a content type."""
214
- if content_type not in self.schedule:
215
- return False
216
- self.schedule[content_type] = {"hour": int(hour), "minute": int(minute)}
217
- self.save()
218
- return True
219
-
220
- def add_content_type(self, type_key, hour, minute):
221
- if type_key in self.schedule:
222
- return False
223
- self.schedule[type_key] = {"hour": int(hour), "minute": int(minute)}
224
- self.save()
225
- return True
226
-
227
- def delete_content_type(self, type_key):
228
- if type_key in self.schedule:
229
- del self.schedule[type_key]
230
- # Also remove from all channel disabled lists to be clean
231
- for ch in self.channels.values():
232
- if type_key in ch.get("disabled_content_types", []):
233
- ch["disabled_content_types"].remove(type_key)
234
- self.save()
235
- return True
236
- return False
237
-
238
- def toggle_channel(self, key):
239
- if key in self.channels:
240
- self.channels[key]["active"] = not self.channels[key]["active"]
241
- self.save()
242
- return self.channels[key]["active"]
243
- return None
244
-
245
- def toggle_content_type(self, channel_key: str, content_type: str) -> bool:
246
- if channel_key not in self.channels:
247
- return False
248
- disabled = self.channels[channel_key].setdefault("disabled_content_types", [])
249
- if content_type in disabled:
250
- disabled.remove(content_type)
251
- enabled = True
252
- else:
253
- disabled.append(content_type)
254
- enabled = False
255
- self.channels[channel_key]["disabled_content_types"] = disabled
256
- self.save()
257
- return enabled
258
-
259
- def is_content_type_enabled(self, channel_key: str, content_type: str) -> bool:
260
- disabled = self.channels.get(channel_key, {}).get("disabled_content_types", [])
261
- return content_type not in disabled
262
-
263
- def toggle_mcq_poll(self, key):
264
- if key in self.channels:
265
- current = self.channels[key].get("mcq_poll_enabled", False)
266
- self.channels[key]["mcq_poll_enabled"] = not current
267
- self.save()
268
- return self.channels[key]["mcq_poll_enabled"]
269
- return None
270
-
271
- def set_mcq_delay(self, key, delay_min: int, delay_max: int):
272
- if key in self.channels:
273
- self.channels[key]["mcq_poll_delay_min"] = int(delay_min)
274
- self.channels[key]["mcq_poll_delay_max"] = int(delay_max)
275
- self.save()
276
- return True
277
- return False
278
-
279
- def update_time(self, content_type, hour, minute):
280
- return self.set_schedule(content_type, hour, minute)
281
-
282
- def update_settings(self, updates: dict):
283
- self.settings.update(updates)
284
- self.save()
285
- return True
286
-
287
- # Singleton instance
288
- config_manager = ConfigManager()
 
1
+ import json
2
+ import os
3
+ import logging
4
+
5
+ logger = logging.getLogger(__name__)
6
+
7
+ CONFIG_FILE = "data/bot_config.json"
8
+
9
+ # Default hardcoded configuration (Seed values)
10
+ DEFAULT_CHANNELS = {
11
+ "jee_main": {
12
+ "id": "@JEE_NEET_Handwritten_Note",
13
+ "label": "JEE Main Daily",
14
+ "exam_focus": ["JEE Main"],
15
+ "subjects": ["physics", "chemistry", "maths"],
16
+ "active": True,
17
+ "mcq_poll_enabled": True,
18
+ "mcq_poll_delay_min": 60,
19
+ "mcq_poll_delay_max": 90,
20
+ # This channel ONLY runs the 10-MCQ Poll Session at 8 PM
21
+ "disabled_content_types": ["pyq_question", "formula_sheet", "short_notes",
22
+ "mnemonic", "concept_recap", "mock_question", "motivational"],
23
+ "footer": "🎯 *Crack JEE Main 2025!*\nπŸ“’ Share with your batch!",
24
+ "button_text": "",
25
+ "button_url": "",
26
+ "hashtags": {
27
+ "pyq": "#JEEMain #PYQ #JEEPrep",
28
+ "formula": "#JEEFormula #JEEMaths #JEEPhysics",
29
+ "notes": "#JEENotes #QuickRevision",
30
+ "mnemonic": "#MemoryTrick #JEETricks",
31
+ "mock": "#JEEMock #PracticeNow",
32
+ "recap": "#JEERecap #ConceptClear",
33
+ },
34
+ },
35
+ "neet": {
36
+ "id": "@NEET_HandwrittenNotes_2026",
37
+ "label": "NEET Daily",
38
+ "exam_focus": ["NEET"],
39
+ "subjects": ["physics", "chemistry", "biology"],
40
+ "active": True,
41
+ "mcq_poll_enabled": False,
42
+ "mcq_poll_delay_min": 60,
43
+ "mcq_poll_delay_max": 90,
44
+ "disabled_content_types": ["pyq_question"], # No quiz polls on this channel
45
+ "footer": "πŸ₯ *Future Doctors β€” Keep Going!*\nπŸ“’ Share with your study group!",
46
+ "button_text": "",
47
+ "button_url": "",
48
+ "hashtags": {
49
+ "pyq": "#NEET #NEETPapers #BiologyPYQ",
50
+ "formula": "#NEETFormula #BiologyFacts",
51
+ "notes": "#NEETNotes #MedicalPrep",
52
+ "mnemonic": "#BioMnemonic #NEETTricks",
53
+ "mock": "#NEETMock #Practice",
54
+ "recap": "#NEETRecap #BioRevision",
55
+ },
56
+ },
57
+ "jee_advanced": {
58
+ "id": "@JEE_ADVANCED_NOTES_2026",
59
+ "label": "JEE Advanced Daily",
60
+ "exam_focus": ["JEE Advanced"],
61
+ "subjects": ["physics", "chemistry", "maths"],
62
+ "active": True,
63
+ "mcq_poll_enabled": False,
64
+ "mcq_poll_delay_min": 60,
65
+ "mcq_poll_delay_max": 90,
66
+ "disabled_content_types": ["pyq_question"], # No quiz polls on this channel
67
+ "footer": "πŸ”₯ *IIT Aspirant β€” You've got this!*\nπŸ“’ Forward to your IIT group!",
68
+ "button_text": "",
69
+ "button_url": "",
70
+ "hashtags": {
71
+ "pyq": "#JEEAdvanced #IIT #HardProblems",
72
+ "formula": "#AdvancedFormula #IITLevel",
73
+ "notes": "#IITNotes #AdvancedConcepts",
74
+ "mnemonic": "#SmartStudy #IITTricks",
75
+ "mock": "#AdvancedMock #IITLevel",
76
+ "recap": "#IITRecap #DeepConcepts",
77
+ },
78
+ }
79
+ }
80
+
81
+ DEFAULT_SCHEDULE = {
82
+ "pyq_question": {"hour": 7, "minute": 0},
83
+ "formula_sheet": {"hour": 9, "minute": 0},
84
+ "short_notes": {"hour": 12, "minute": 0},
85
+ "mnemonic": {"hour": 15, "minute": 0},
86
+ "concept_recap": {"hour": 18, "minute": 0},
87
+ "mock_question": {"hour": 20, "minute": 0},
88
+ "motivational": {"hour": 22, "minute": 0},
89
+ # MCQ Poll Session β€” runs INDEPENDENTLY (not via normal post_content loop)
90
+ # hour/minute = when the session STARTS; polls trickle every 60-90s after
91
+ "mcq_session": {"hour": 20, "minute": 0},
92
+ }
93
+
94
+ DEFAULT_SETTINGS = {
95
+ "main_channel_name": "NEET Notes",
96
+ "main_channel_url": "https://t.me/NEET_HandwrittenNotes_2026",
97
+ "dashboard_url": "https://huggingface.co/spaces/H3y-sam/TELEGRAM-BOT/",
98
+ "bot_name": "JEE & NEET Assistant"
99
+ }
100
+
101
+ class ConfigManager:
102
+ def __init__(self):
103
+ self.channels = DEFAULT_CHANNELS
104
+ self.schedule = DEFAULT_SCHEDULE
105
+ self.settings = DEFAULT_SETTINGS
106
+ self.load()
107
+
108
+ def load(self):
109
+ """Load configuration from Gist (remote) or JSON file (local)."""
110
+ # 1. Try to pull from Gist first (remote persistence)
111
+ from content.remote_storage import pull_from_gist
112
+ remote_data = pull_from_gist(os.path.basename(CONFIG_FILE))
113
+ if remote_data:
114
+ if "channels" in remote_data: self.channels = remote_data["channels"]
115
+ if "schedule" in remote_data: self.schedule = remote_data["schedule"]
116
+ if "settings" in remote_data: self.settings.update(remote_data["settings"])
117
+ logger.info(f"[OK] Config loaded from Gist")
118
+ # Save locally to stay in sync
119
+ self._save_local()
120
+ return
121
+
122
+ # 2. Fallback to local file
123
+ if os.path.exists(CONFIG_FILE):
124
+ try:
125
+ with open(CONFIG_FILE, "r") as f:
126
+ data = json.load(f)
127
+ if "channels" in data: self.channels = data["channels"]
128
+ if "schedule" in data: self.schedule = data["schedule"]
129
+ if "settings" in data: self.settings.update(data["settings"])
130
+ logger.info(f"[OK] Dynamic config loaded from {CONFIG_FILE}")
131
+ except Exception as e:
132
+ logger.error(f"[ERROR] Failed to load dynamic config: {e}. Using defaults.")
133
+
134
+ def _save_local(self):
135
+ """Internal helper to save config to local file."""
136
+ try:
137
+ os.makedirs(os.path.dirname(CONFIG_FILE), exist_ok=True)
138
+ temp_file = CONFIG_FILE + ".tmp"
139
+ with open(temp_file, "w") as f:
140
+ json.dump({
141
+ "channels": self.channels,
142
+ "schedule": self.schedule,
143
+ "settings": self.settings
144
+ }, f, indent=4)
145
+ os.replace(temp_file, CONFIG_FILE)
146
+ except Exception as e:
147
+ logger.error(f"[LOCAL SAVE ERROR] {e}")
148
+
149
+ def save(self):
150
+ """Save current configuration to local file AND GitHub Gist."""
151
+ # 1. Save locally
152
+ self._save_local()
153
+ logger.info(f"[OK] Dynamic config saved locally to {CONFIG_FILE}")
154
+
155
+ # 2. Push to Gist
156
+ from content.remote_storage import push_to_gist
157
+ push_to_gist(os.path.basename(CONFIG_FILE), {
158
+ "channels": self.channels,
159
+ "schedule": self.schedule,
160
+ "settings": self.settings
161
+ })
162
+
163
+ def add_channel(self, key: str, channel_id: str, label: str,
164
+ exam_focus: list = None, subjects: list = None,
165
+ mcq_only: bool = False) -> bool:
166
+ """Add a new channel. Returns False if key already exists."""
167
+ if key in self.channels:
168
+ return False
169
+ disabled = ["pyq_question", "formula_sheet", "short_notes",
170
+ "mnemonic", "concept_recap", "mock_question", "motivational"] if mcq_only else []
171
+ self.channels[key] = {
172
+ "id": channel_id,
173
+ "label": label,
174
+ "exam_focus": exam_focus or ["JEE Main"],
175
+ "subjects": subjects or ["physics", "chemistry", "maths"],
176
+ "active": True,
177
+ "mcq_poll_enabled": mcq_only,
178
+ "mcq_poll_delay_min": 60,
179
+ "mcq_poll_delay_max": 90,
180
+ "disabled_content_types": disabled,
181
+ "footer": "πŸ“’ Share with your batch!\nπŸ”— @xcrazylearners",
182
+ "button_text": "",
183
+ "button_url": "",
184
+ "hashtags": {
185
+ "pyq": "#JEEMain #PYQ",
186
+ "formula": "#Formula #Notes",
187
+ "notes": "#Notes #Revision",
188
+ "mnemonic": "#MemoryTrick",
189
+ "mock": "#Mock #Practice",
190
+ "recap": "#Recap #Concept",
191
+ }
192
+ }
193
+ self.save()
194
+ return True
195
+
196
+ def delete_channel(self, key: str) -> bool:
197
+ """Remove a channel from configuration."""
198
+ if key not in self.channels:
199
+ return False
200
+ del self.channels[key]
201
+ self.save()
202
+ return True
203
+
204
+ def update_channel(self, key: str, updates: dict) -> bool:
205
+ """Patch specific fields of a channel config."""
206
+ if key not in self.channels:
207
+ return False
208
+ self.channels[key].update(updates)
209
+ self.save()
210
+ return True
211
+
212
+ def set_schedule(self, content_type: str, hour: int, minute: int) -> bool:
213
+ """Update posting time for a content type."""
214
+ if content_type not in self.schedule:
215
+ return False
216
+ self.schedule[content_type] = {"hour": int(hour), "minute": int(minute)}
217
+ self.save()
218
+ return True
219
+
220
+ def add_content_type(self, type_key, hour, minute):
221
+ if type_key in self.schedule:
222
+ return False
223
+ self.schedule[type_key] = {"hour": int(hour), "minute": int(minute)}
224
+ self.save()
225
+ return True
226
+
227
+ def delete_content_type(self, type_key):
228
+ if type_key in self.schedule:
229
+ del self.schedule[type_key]
230
+ # Also remove from all channel disabled lists to be clean
231
+ for ch in self.channels.values():
232
+ if type_key in ch.get("disabled_content_types", []):
233
+ ch["disabled_content_types"].remove(type_key)
234
+ self.save()
235
+ return True
236
+ return False
237
+
238
+ def toggle_channel(self, key):
239
+ if key in self.channels:
240
+ self.channels[key]["active"] = not self.channels[key]["active"]
241
+ self.save()
242
+ return self.channels[key]["active"]
243
+ return None
244
+
245
+ def toggle_content_type(self, channel_key: str, content_type: str) -> bool:
246
+ if channel_key not in self.channels:
247
+ return False
248
+ disabled = self.channels[channel_key].setdefault("disabled_content_types", [])
249
+ if content_type in disabled:
250
+ disabled.remove(content_type)
251
+ enabled = True
252
+ else:
253
+ disabled.append(content_type)
254
+ enabled = False
255
+ self.channels[channel_key]["disabled_content_types"] = disabled
256
+ self.save()
257
+ return enabled
258
+
259
+ def is_content_type_enabled(self, channel_key: str, content_type: str) -> bool:
260
+ disabled = self.channels.get(channel_key, {}).get("disabled_content_types", [])
261
+ return content_type not in disabled
262
+
263
+ def toggle_mcq_poll(self, key):
264
+ if key in self.channels:
265
+ current = self.channels[key].get("mcq_poll_enabled", False)
266
+ self.channels[key]["mcq_poll_enabled"] = not current
267
+ self.save()
268
+ return self.channels[key]["mcq_poll_enabled"]
269
+ return None
270
+
271
+ def set_mcq_delay(self, key, delay_min: int, delay_max: int):
272
+ if key in self.channels:
273
+ self.channels[key]["mcq_poll_delay_min"] = int(delay_min)
274
+ self.channels[key]["mcq_poll_delay_max"] = int(delay_max)
275
+ self.save()
276
+ return True
277
+ return False
278
+
279
+ def update_time(self, content_type, hour, minute):
280
+ return self.set_schedule(content_type, hour, minute)
281
+
282
+ def update_settings(self, updates: dict):
283
+ self.settings.update(updates)
284
+ self.save()
285
+ return True
286
+
287
+ # Singleton instance
288
+ config_manager = ConfigManager()
content/database.py CHANGED
@@ -1,257 +1,257 @@
1
- import sqlite3
2
- import logging
3
- import os
4
- import json
5
- import re
6
-
7
- logger = logging.getLogger(__name__)
8
- DB_PATH = "data/bot_data.db"
9
- SEEN_NEWS_FILE = "data/seen_news.json"
10
- _seen_news_cache = {}
11
-
12
- def load_seen_news():
13
- global _seen_news_cache
14
- try:
15
- from content.remote_storage import pull_from_gist
16
- pulled = pull_from_gist("seen_news.json")
17
- if pulled and isinstance(pulled, dict):
18
- _seen_news_cache = pulled
19
- logger.info(f"Loaded {len(_seen_news_cache)} seen news items from Gist.")
20
- # Sync to SQLite
21
- conn = sqlite3.connect(DB_PATH)
22
- cursor = conn.cursor()
23
- for t, l in _seen_news_cache.items():
24
- cursor.execute("INSERT OR IGNORE INTO seen_news (title, link) VALUES (?, ?)", (t, l))
25
- conn.commit()
26
- conn.close()
27
- return
28
- except Exception as e:
29
- logger.error(f"Error loading seen news from Gist: {e}")
30
-
31
- # Fallback to local
32
- if os.path.exists(SEEN_NEWS_FILE):
33
- try:
34
- with open(SEEN_NEWS_FILE, "r") as f:
35
- _seen_news_cache = json.load(f)
36
- except Exception as e:
37
- logger.error(f"Local seen news load error: {e}")
38
- _seen_news_cache = {}
39
-
40
- # Ensure database is initialised before calling load_seen_news
41
- def init_db():
42
- os.makedirs("data", exist_ok=True)
43
- conn = sqlite3.connect(DB_PATH)
44
- cursor = conn.cursor()
45
-
46
- # Leaderboard table
47
- # We track scores per user per channel to keep it fair
48
- cursor.execute("""
49
- CREATE TABLE IF NOT EXISTS leaderboard (
50
- user_id INTEGER,
51
- channel_id TEXT,
52
- username TEXT,
53
- full_name TEXT,
54
- score INTEGER DEFAULT 0,
55
- streak INTEGER DEFAULT 0,
56
- last_streak_date TEXT,
57
- last_active TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
58
- PRIMARY KEY (user_id, channel_id)
59
- )
60
- """)
61
-
62
- # News tracker table to avoid duplicates
63
- # Uses title as unique identifier for permanent deduplication
64
- cursor.execute("""
65
- CREATE TABLE IF NOT EXISTS seen_news (
66
- title TEXT PRIMARY KEY,
67
- link TEXT UNIQUE,
68
- fetch_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP
69
- )
70
- """)
71
-
72
- # Poll tracker to know which option is correct for a given poll_id
73
- cursor.execute("""
74
- CREATE TABLE IF NOT EXISTS poll_tracker (
75
- poll_id TEXT PRIMARY KEY,
76
- channel_id TEXT,
77
- message_id INTEGER,
78
- correct_index INTEGER,
79
- explanation TEXT
80
- )
81
- """)
82
-
83
- conn.commit()
84
- conn.close()
85
-
86
- # Now load the Gist-synced cache after DB init
87
- load_seen_news()
88
-
89
- def update_score(user_id, channel_id, username, full_name, points=1):
90
- try:
91
- conn = sqlite3.connect(DB_PATH)
92
- cursor = conn.cursor()
93
- cursor.execute("""
94
- INSERT INTO leaderboard (user_id, channel_id, username, full_name, score)
95
- VALUES (?, ?, ?, ?, ?)
96
- ON CONFLICT(user_id, channel_id) DO UPDATE SET
97
- score = score + ?,
98
- username = ?,
99
- full_name = ?,
100
- last_active = CURRENT_TIMESTAMP
101
- """, (user_id, channel_id, username, full_name, points, points, username, full_name))
102
- conn.commit()
103
- conn.close()
104
- except Exception as e:
105
- logger.error(f"DB Error (update_score): {e}")
106
-
107
- def get_top_students(channel_id, limit=10):
108
- try:
109
- conn = sqlite3.connect(DB_PATH)
110
- cursor = conn.cursor()
111
- cursor.execute("""
112
- SELECT username, full_name, score FROM leaderboard
113
- WHERE channel_id = ?
114
- ORDER BY score DESC, last_active DESC
115
- LIMIT ?
116
- """, (channel_id, limit))
117
- rows = cursor.fetchall()
118
- conn.close()
119
- return rows
120
- except Exception as e:
121
- logger.error(f"DB Error (get_top_students): {e}")
122
- return []
123
-
124
- def clear_weekly_scores():
125
- """Reset scores for the new week (run by scheduler)"""
126
- try:
127
- conn = sqlite3.connect(DB_PATH)
128
- cursor = conn.cursor()
129
- cursor.execute("UPDATE leaderboard SET score = 0")
130
- conn.commit()
131
- conn.close()
132
- except Exception as e:
133
- logger.error(f"DB Error (clear_scores): {e}")
134
-
135
- def is_news_seen(title):
136
- """Check if a news item with this exact title has been posted before (case & space insensitive)."""
137
- cleaned_title = re.sub(r'\s+', ' ', title).strip().lower()
138
-
139
- # 1. Check local cache memory
140
- for cached_title in _seen_news_cache:
141
- if re.sub(r'\s+', ' ', cached_title).strip().lower() == cleaned_title:
142
- return True
143
-
144
- # 2. Check local database
145
- try:
146
- conn = sqlite3.connect(DB_PATH)
147
- cursor = conn.cursor()
148
- cursor.execute("SELECT title FROM seen_news")
149
- rows = cursor.fetchall()
150
- conn.close()
151
- for (t,) in rows:
152
- if re.sub(r'\s+', ' ', t).strip().lower() == cleaned_title:
153
- return True
154
- except Exception as e:
155
- logger.error(f"Error checking seen news in SQLite: {e}")
156
-
157
- return False
158
-
159
- def mark_news_seen(title, link=""):
160
- """Mark a news item as seen. Uses title as unique identifier."""
161
- # Update local cache memory
162
- _seen_news_cache[title] = link
163
-
164
- # Save to local file
165
- try:
166
- os.makedirs("data", exist_ok=True)
167
- with open(SEEN_NEWS_FILE, "w") as f:
168
- json.dump(_seen_news_cache, f, indent=2)
169
- except Exception as e:
170
- logger.error(f"Error saving seen news to local JSON: {e}")
171
-
172
- # Push to Gist
173
- try:
174
- from content.remote_storage import push_to_gist
175
- push_to_gist("seen_news.json", _seen_news_cache)
176
- except Exception as e:
177
- logger.error(f"Error pushing seen news to Gist: {e}")
178
-
179
- # Save to SQLite
180
- try:
181
- conn = sqlite3.connect(DB_PATH)
182
- cursor = conn.cursor()
183
- cursor.execute("INSERT OR IGNORE INTO seen_news (title, link) VALUES (?, ?)", (title, link))
184
- conn.commit()
185
- conn.close()
186
- except Exception as e:
187
- logger.error(f"Error marking news seen in SQLite: {e}")
188
-
189
- def track_poll(poll_id, channel_id, message_id, correct_index, explanation=None):
190
- conn = sqlite3.connect(DB_PATH)
191
- cursor = conn.cursor()
192
- cursor.execute("INSERT INTO poll_tracker (poll_id, channel_id, message_id, correct_index, explanation) VALUES (?, ?, ?, ?, ?)",
193
- (poll_id, channel_id, message_id, correct_index, explanation))
194
- conn.commit()
195
- conn.close()
196
-
197
- def get_poll_data(poll_id):
198
- conn = sqlite3.connect(DB_PATH)
199
- cursor = conn.cursor()
200
- cursor.execute("SELECT channel_id, message_id, correct_index FROM poll_tracker WHERE poll_id = ?", (poll_id,))
201
- res = cursor.fetchone()
202
- conn.close()
203
- return res # returns (channel_id, message_id, correct_index) or None
204
-
205
- def get_poll_explanation(poll_id):
206
- conn = sqlite3.connect(DB_PATH)
207
- cursor = conn.cursor()
208
- cursor.execute("SELECT explanation FROM poll_tracker WHERE poll_id = ?", (poll_id,))
209
- res = cursor.fetchone()
210
- conn.close()
211
- return res[0] if res else None
212
-
213
- def update_streak(user_id, channel_id):
214
- """
215
- Update user's daily streak.
216
- Returns (new_streak, increased)
217
- """
218
- from datetime import datetime
219
- today = datetime.now().strftime("%Y-%m-%d")
220
- yesterday = (datetime.now().timestamp() - 86400)
221
- yesterday_str = datetime.fromtimestamp(yesterday).strftime("%Y-%m-%d")
222
-
223
- try:
224
- conn = sqlite3.connect(DB_PATH)
225
- cursor = conn.cursor()
226
-
227
- # Get current streak info
228
- cursor.execute("SELECT streak, last_streak_date FROM leaderboard WHERE user_id = ? AND channel_id = ?", (user_id, channel_id))
229
- row = cursor.fetchone()
230
-
231
- if not row:
232
- # New user entry will be handled by update_score, but we can init here
233
- cursor.execute("INSERT OR IGNORE INTO leaderboard (user_id, channel_id, streak, last_streak_date) VALUES (?, ?, ?, ?)",
234
- (user_id, channel_id, 1, today))
235
- conn.commit()
236
- conn.close()
237
- return 1, True
238
-
239
- streak, last_date = row
240
-
241
- if last_date == today:
242
- conn.close()
243
- return streak, False # Already updated today
244
-
245
- if last_date == yesterday_str:
246
- new_streak = streak + 1
247
- else:
248
- new_streak = 1 # Streak broken
249
-
250
- cursor.execute("UPDATE leaderboard SET streak = ?, last_streak_date = ? WHERE user_id = ? AND channel_id = ?",
251
- (new_streak, today, user_id, channel_id))
252
- conn.commit()
253
- conn.close()
254
- return new_streak, True
255
- except Exception as e:
256
- logger.error(f"DB Error (update_streak): {e}")
257
- return 0, False
 
1
+ import sqlite3
2
+ import logging
3
+ import os
4
+ import json
5
+ import re
6
+
7
+ logger = logging.getLogger(__name__)
8
+ DB_PATH = "data/bot_data.db"
9
+ SEEN_NEWS_FILE = "data/seen_news.json"
10
+ _seen_news_cache = {}
11
+
12
+ def load_seen_news():
13
+ global _seen_news_cache
14
+ try:
15
+ from content.remote_storage import pull_from_gist
16
+ pulled = pull_from_gist("seen_news.json")
17
+ if pulled and isinstance(pulled, dict):
18
+ _seen_news_cache = pulled
19
+ logger.info(f"Loaded {len(_seen_news_cache)} seen news items from Gist.")
20
+ # Sync to SQLite
21
+ conn = sqlite3.connect(DB_PATH)
22
+ cursor = conn.cursor()
23
+ for t, l in _seen_news_cache.items():
24
+ cursor.execute("INSERT OR IGNORE INTO seen_news (title, link) VALUES (?, ?)", (t, l))
25
+ conn.commit()
26
+ conn.close()
27
+ return
28
+ except Exception as e:
29
+ logger.error(f"Error loading seen news from Gist: {e}")
30
+
31
+ # Fallback to local
32
+ if os.path.exists(SEEN_NEWS_FILE):
33
+ try:
34
+ with open(SEEN_NEWS_FILE, "r") as f:
35
+ _seen_news_cache = json.load(f)
36
+ except Exception as e:
37
+ logger.error(f"Local seen news load error: {e}")
38
+ _seen_news_cache = {}
39
+
40
+ # Ensure database is initialised before calling load_seen_news
41
+ def init_db():
42
+ os.makedirs("data", exist_ok=True)
43
+ conn = sqlite3.connect(DB_PATH)
44
+ cursor = conn.cursor()
45
+
46
+ # Leaderboard table
47
+ # We track scores per user per channel to keep it fair
48
+ cursor.execute("""
49
+ CREATE TABLE IF NOT EXISTS leaderboard (
50
+ user_id INTEGER,
51
+ channel_id TEXT,
52
+ username TEXT,
53
+ full_name TEXT,
54
+ score INTEGER DEFAULT 0,
55
+ streak INTEGER DEFAULT 0,
56
+ last_streak_date TEXT,
57
+ last_active TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
58
+ PRIMARY KEY (user_id, channel_id)
59
+ )
60
+ """)
61
+
62
+ # News tracker table to avoid duplicates
63
+ # Uses title as unique identifier for permanent deduplication
64
+ cursor.execute("""
65
+ CREATE TABLE IF NOT EXISTS seen_news (
66
+ title TEXT PRIMARY KEY,
67
+ link TEXT UNIQUE,
68
+ fetch_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP
69
+ )
70
+ """)
71
+
72
+ # Poll tracker to know which option is correct for a given poll_id
73
+ cursor.execute("""
74
+ CREATE TABLE IF NOT EXISTS poll_tracker (
75
+ poll_id TEXT PRIMARY KEY,
76
+ channel_id TEXT,
77
+ message_id INTEGER,
78
+ correct_index INTEGER,
79
+ explanation TEXT
80
+ )
81
+ """)
82
+
83
+ conn.commit()
84
+ conn.close()
85
+
86
+ # Now load the Gist-synced cache after DB init
87
+ load_seen_news()
88
+
89
+ def update_score(user_id, channel_id, username, full_name, points=1):
90
+ try:
91
+ conn = sqlite3.connect(DB_PATH)
92
+ cursor = conn.cursor()
93
+ cursor.execute("""
94
+ INSERT INTO leaderboard (user_id, channel_id, username, full_name, score)
95
+ VALUES (?, ?, ?, ?, ?)
96
+ ON CONFLICT(user_id, channel_id) DO UPDATE SET
97
+ score = score + ?,
98
+ username = ?,
99
+ full_name = ?,
100
+ last_active = CURRENT_TIMESTAMP
101
+ """, (user_id, channel_id, username, full_name, points, points, username, full_name))
102
+ conn.commit()
103
+ conn.close()
104
+ except Exception as e:
105
+ logger.error(f"DB Error (update_score): {e}")
106
+
107
+ def get_top_students(channel_id, limit=10):
108
+ try:
109
+ conn = sqlite3.connect(DB_PATH)
110
+ cursor = conn.cursor()
111
+ cursor.execute("""
112
+ SELECT username, full_name, score FROM leaderboard
113
+ WHERE channel_id = ?
114
+ ORDER BY score DESC, last_active DESC
115
+ LIMIT ?
116
+ """, (channel_id, limit))
117
+ rows = cursor.fetchall()
118
+ conn.close()
119
+ return rows
120
+ except Exception as e:
121
+ logger.error(f"DB Error (get_top_students): {e}")
122
+ return []
123
+
124
+ def clear_weekly_scores():
125
+ """Reset scores for the new week (run by scheduler)"""
126
+ try:
127
+ conn = sqlite3.connect(DB_PATH)
128
+ cursor = conn.cursor()
129
+ cursor.execute("UPDATE leaderboard SET score = 0")
130
+ conn.commit()
131
+ conn.close()
132
+ except Exception as e:
133
+ logger.error(f"DB Error (clear_scores): {e}")
134
+
135
+ def is_news_seen(title):
136
+ """Check if a news item with this exact title has been posted before (case & space insensitive)."""
137
+ cleaned_title = re.sub(r'\s+', ' ', title).strip().lower()
138
+
139
+ # 1. Check local cache memory
140
+ for cached_title in _seen_news_cache:
141
+ if re.sub(r'\s+', ' ', cached_title).strip().lower() == cleaned_title:
142
+ return True
143
+
144
+ # 2. Check local database
145
+ try:
146
+ conn = sqlite3.connect(DB_PATH)
147
+ cursor = conn.cursor()
148
+ cursor.execute("SELECT title FROM seen_news")
149
+ rows = cursor.fetchall()
150
+ conn.close()
151
+ for (t,) in rows:
152
+ if re.sub(r'\s+', ' ', t).strip().lower() == cleaned_title:
153
+ return True
154
+ except Exception as e:
155
+ logger.error(f"Error checking seen news in SQLite: {e}")
156
+
157
+ return False
158
+
159
+ def mark_news_seen(title, link=""):
160
+ """Mark a news item as seen. Uses title as unique identifier."""
161
+ # Update local cache memory
162
+ _seen_news_cache[title] = link
163
+
164
+ # Save to local file
165
+ try:
166
+ os.makedirs("data", exist_ok=True)
167
+ with open(SEEN_NEWS_FILE, "w") as f:
168
+ json.dump(_seen_news_cache, f, indent=2)
169
+ except Exception as e:
170
+ logger.error(f"Error saving seen news to local JSON: {e}")
171
+
172
+ # Push to Gist
173
+ try:
174
+ from content.remote_storage import push_to_gist
175
+ push_to_gist("seen_news.json", _seen_news_cache)
176
+ except Exception as e:
177
+ logger.error(f"Error pushing seen news to Gist: {e}")
178
+
179
+ # Save to SQLite
180
+ try:
181
+ conn = sqlite3.connect(DB_PATH)
182
+ cursor = conn.cursor()
183
+ cursor.execute("INSERT OR IGNORE INTO seen_news (title, link) VALUES (?, ?)", (title, link))
184
+ conn.commit()
185
+ conn.close()
186
+ except Exception as e:
187
+ logger.error(f"Error marking news seen in SQLite: {e}")
188
+
189
+ def track_poll(poll_id, channel_id, message_id, correct_index, explanation=None):
190
+ conn = sqlite3.connect(DB_PATH)
191
+ cursor = conn.cursor()
192
+ cursor.execute("INSERT INTO poll_tracker (poll_id, channel_id, message_id, correct_index, explanation) VALUES (?, ?, ?, ?, ?)",
193
+ (poll_id, channel_id, message_id, correct_index, explanation))
194
+ conn.commit()
195
+ conn.close()
196
+
197
+ def get_poll_data(poll_id):
198
+ conn = sqlite3.connect(DB_PATH)
199
+ cursor = conn.cursor()
200
+ cursor.execute("SELECT channel_id, message_id, correct_index FROM poll_tracker WHERE poll_id = ?", (poll_id,))
201
+ res = cursor.fetchone()
202
+ conn.close()
203
+ return res # returns (channel_id, message_id, correct_index) or None
204
+
205
+ def get_poll_explanation(poll_id):
206
+ conn = sqlite3.connect(DB_PATH)
207
+ cursor = conn.cursor()
208
+ cursor.execute("SELECT explanation FROM poll_tracker WHERE poll_id = ?", (poll_id,))
209
+ res = cursor.fetchone()
210
+ conn.close()
211
+ return res[0] if res else None
212
+
213
+ def update_streak(user_id, channel_id):
214
+ """
215
+ Update user's daily streak.
216
+ Returns (new_streak, increased)
217
+ """
218
+ from datetime import datetime
219
+ today = datetime.now().strftime("%Y-%m-%d")
220
+ yesterday = (datetime.now().timestamp() - 86400)
221
+ yesterday_str = datetime.fromtimestamp(yesterday).strftime("%Y-%m-%d")
222
+
223
+ try:
224
+ conn = sqlite3.connect(DB_PATH)
225
+ cursor = conn.cursor()
226
+
227
+ # Get current streak info
228
+ cursor.execute("SELECT streak, last_streak_date FROM leaderboard WHERE user_id = ? AND channel_id = ?", (user_id, channel_id))
229
+ row = cursor.fetchone()
230
+
231
+ if not row:
232
+ # New user entry will be handled by update_score, but we can init here
233
+ cursor.execute("INSERT OR IGNORE INTO leaderboard (user_id, channel_id, streak, last_streak_date) VALUES (?, ?, ?, ?)",
234
+ (user_id, channel_id, 1, today))
235
+ conn.commit()
236
+ conn.close()
237
+ return 1, True
238
+
239
+ streak, last_date = row
240
+
241
+ if last_date == today:
242
+ conn.close()
243
+ return streak, False # Already updated today
244
+
245
+ if last_date == yesterday_str:
246
+ new_streak = streak + 1
247
+ else:
248
+ new_streak = 1 # Streak broken
249
+
250
+ cursor.execute("UPDATE leaderboard SET streak = ?, last_streak_date = ? WHERE user_id = ? AND channel_id = ?",
251
+ (new_streak, today, user_id, channel_id))
252
+ conn.commit()
253
+ conn.close()
254
+ return new_streak, True
255
+ except Exception as e:
256
+ logger.error(f"DB Error (update_streak): {e}")
257
+ return 0, False
content/history.py CHANGED
@@ -1,256 +1,256 @@
1
- """
2
- Content History Tracker
3
- Tracks what has been posted to each channel to prevent topic repetition.
4
- Uses a JSON file for persistence across bot restarts.
5
-
6
- Storage key structure:
7
- history[channel_key][content_type][subject] = deque of past chapter names
8
- """
9
-
10
- import json
11
- import logging
12
- import os
13
- from collections import deque
14
- from threading import Lock
15
- from config import HISTORY_FILE, HISTORY_DEPTH
16
- from content.config_manager import config_manager
17
- from content.syllabus_manager import syllabus_manager
18
- from content.remote_storage import pull_history_from_gist, push_history_to_gist
19
-
20
- logger = logging.getLogger(__name__)
21
- _lock = Lock()
22
-
23
-
24
- def _load() -> dict:
25
- serialisable = {}
26
-
27
- # 1. Try pulling from Remote first (Hugging Face / Gist)
28
- remote_data = pull_history_from_gist()
29
- if remote_data:
30
- serialisable = remote_data
31
-
32
- # 2. Otherwise try Local
33
- elif os.path.exists(HISTORY_FILE):
34
- try:
35
- with open(HISTORY_FILE, "r") as f:
36
- serialisable = json.load(f)
37
- except Exception as e:
38
- logger.error(f"Local history load error: {e}")
39
- return {}
40
- else:
41
- return {}
42
-
43
- try:
44
- # Convert lists back to deques with maxlen
45
- result = {}
46
- for ch in serialisable:
47
- if ch == "weekly_archive":
48
- continue
49
- result[ch] = {}
50
- for ct in serialisable[ch]:
51
- result[ch][ct] = {}
52
- for subj, items in serialisable[ch][ct].items():
53
- result[ch][ct][subj] = deque(items, maxlen=HISTORY_DEPTH)
54
-
55
- # Load weekly archive separately
56
- result["weekly_archive"] = serialisable.get("weekly_archive", {})
57
-
58
- return result
59
- except Exception as e:
60
- logger.error(f"History load error: {e}")
61
- return {}
62
-
63
-
64
- def _save(history: dict):
65
- try:
66
- os.makedirs(os.path.dirname(HISTORY_FILE), exist_ok=True)
67
- serialisable = {}
68
- for ch in history:
69
- if ch == "weekly_archive":
70
- continue
71
- serialisable[ch] = {}
72
- for ct in history[ch]:
73
- serialisable[ch][ct] = {}
74
- for subj, dq in history[ch][ct].items():
75
- serialisable[ch][ct][subj] = list(dq)
76
-
77
- serialisable["weekly_archive"] = history.get("weekly_archive", {})
78
-
79
- # 1. Save Local
80
- with open(HISTORY_FILE, "w") as f:
81
- json.dump(serialisable, f, indent=2)
82
-
83
- # 2. Push to Remote (Gist)
84
- push_history_to_gist(serialisable)
85
-
86
- except Exception as e:
87
- logger.error(f"History save error: {e}")
88
-
89
-
90
- # Module-level cache β€” loaded once, written on every update
91
- _history = _load()
92
-
93
-
94
- def pick_fresh_chapter(channel_key: str, content_type: str, subject: str) -> str:
95
- """
96
- Pick a chapter from the official syllabus that hasn't been recently used
97
- for this (channel Γ— content_type Γ— subject) combination.
98
- """
99
- with _lock:
100
- # Determine the exam focus for this channel
101
- channel_cfg = config_manager.channels.get(channel_key, {})
102
- exam_focus = channel_cfg.get("exam_focus", ["JEE Main"])
103
-
104
- # Get flattened chapters for this focus + subject
105
- all_chapters = syllabus_manager.get_chapters(exam_focus, subject)
106
-
107
- if not all_chapters:
108
- return "General"
109
-
110
- used = (
111
- _history
112
- .get(channel_key, {})
113
- .get(content_type, {})
114
- .get(subject, deque(maxlen=HISTORY_DEPTH))
115
- )
116
- used_set = set(used)
117
-
118
- # Prefer chapters never used
119
- fresh = [c for c in all_chapters if c not in used_set]
120
-
121
- if fresh:
122
- import random
123
- chapter = random.choice(fresh)
124
- else:
125
- # All chapters used β€” pick the one used longest ago (front of deque)
126
- oldest_used = list(used)
127
- # Pick from oldest half
128
- oldest_half = oldest_used[:max(1, len(oldest_used) // 2)]
129
- import random
130
- chapter = random.choice(oldest_half)
131
- logger.info(f"All chapters used for {channel_key}/{content_type}/{subject}, recycling oldest: {chapter}")
132
-
133
- # Record this pick
134
- _history \
135
- .setdefault(channel_key, {}) \
136
- .setdefault(content_type, {}) \
137
- .setdefault(subject, deque(maxlen=HISTORY_DEPTH)) \
138
- .append(chapter)
139
-
140
- _save(_history)
141
- return chapter
142
-
143
-
144
- def get_channel_history_summary(channel_key: str) -> dict:
145
- """Return a summary of how many unique chapters have been covered per subject."""
146
- ch_data = _history.get(channel_key, {})
147
- summary = {}
148
- for content_type, subjects in ch_data.items():
149
- summary[content_type] = {
150
- subj: list(chapters)
151
- for subj, chapters in subjects.items()
152
- }
153
- return summary
154
-
155
-
156
- def clear_channel_history(channel_key: str):
157
- """Reset history for a specific channel (admin action)."""
158
- with _lock:
159
- if channel_key in _history:
160
- del _history[channel_key]
161
- _save(_history)
162
- logger.info(f"Cleared history for channel: {channel_key}")
163
-
164
-
165
- def get_coverage_stats() -> dict:
166
- """
167
- Returns per-channel coverage stats.
168
- """
169
- stats = {}
170
- for ch_key, ch_data in _history.items():
171
- if ch_key == "weekly_archive": continue
172
- channel_cfg = config_manager.channels.get(ch_key, {})
173
- exam_focus = channel_cfg.get("exam_focus", ["JEE Main"])
174
-
175
- stats[ch_key] = {}
176
- for ct, subjects in ch_data.items():
177
- covered = sum(len(set(list(chapters))) for chapters in subjects.values())
178
- total = sum(len(syllabus_manager.get_chapters(exam_focus, s)) for s in subjects)
179
- stats[ch_key][ct] = {
180
- "covered": covered,
181
- "total": total,
182
- "pct": round(covered / total * 100, 1) if total else 0,
183
- }
184
- return stats
185
-
186
-
187
- def get_channel_stats(channel_key: str) -> dict:
188
- """Detailed stats for ONE channel, grouped by Subject."""
189
- # Determine exam focus
190
- channel_cfg = config_manager.channels.get(channel_key, {})
191
- exam_focus = channel_cfg.get("exam_focus", ["JEE Main"])
192
-
193
- # FIX: initialise ch_data and stats before using them
194
- ch_data = _history.get(channel_key, {})
195
- stats = {}
196
-
197
- # Combine all content types for a total subject view
198
- for ct, subjects in ch_data.items():
199
- for subj, chapters in subjects.items():
200
- if subj not in stats:
201
- total_chapters = len(syllabus_manager.get_chapters(exam_focus, subj))
202
- stats[subj] = {"covered": set(), "total": total_chapters}
203
- stats[subj]["covered"].update(list(chapters))
204
-
205
- # Calculate final percentages
206
- result = {}
207
- for subj, data in stats.items():
208
- covered_count = len(data["covered"])
209
- total_count = data["total"]
210
- result[subj] = {
211
- "covered": covered_count,
212
- "total": total_count,
213
- "pct": round(covered_count / total_count * 100, 1) if total_count else 0
214
- }
215
- return result
216
-
217
-
218
- # ─────────────────────────────────────────────
219
- # Weekly Archive Helpers (for PDF Digest)
220
- # ─────────────────────────────────────────────
221
-
222
- def archive_weekly_post(channel_key: str, content_type: str, subject: str, chapter: str, text: str):
223
- """Save the full text of a post for the Sunday PDF compilation."""
224
- with _lock:
225
- archive = _history.setdefault("weekly_archive", {})
226
- ch_archive = archive.setdefault(channel_key, {})
227
- ct_archive = ch_archive.setdefault(content_type, [])
228
-
229
- # Append as a structured entry
230
- from datetime import datetime as _dt
231
- ct_archive.append({
232
- "subject": subject,
233
- "chapter": chapter,
234
- "text": text,
235
- "date": _dt.now().strftime("%d %b %Y") # actual date, not env var
236
- })
237
- _save(_history)
238
- logger.info(f"Archived [{content_type}] for {channel_key} weekly digest.")
239
-
240
-
241
- def get_weekly_archive(channel_key: str, content_type: str) -> list:
242
- """Retrieve the week's archived posts for a channel and type."""
243
- return _history.get("weekly_archive", {}).get(channel_key, {}).get(content_type, [])
244
-
245
-
246
- def clear_weekly_archive(channel_key: str = None):
247
- """Clear the weekly archive after the PDF is posted."""
248
- with _lock:
249
- if "weekly_archive" in _history:
250
- if channel_key:
251
- if channel_key in _history["weekly_archive"]:
252
- _history["weekly_archive"][channel_key] = {}
253
- else:
254
- _history["weekly_archive"] = {}
255
- _save(_history)
256
- logger.info(f"Cleared weekly archive {f'for {channel_key}' if channel_key else 'completely'}.")
 
1
+ """
2
+ Content History Tracker
3
+ Tracks what has been posted to each channel to prevent topic repetition.
4
+ Uses a JSON file for persistence across bot restarts.
5
+
6
+ Storage key structure:
7
+ history[channel_key][content_type][subject] = deque of past chapter names
8
+ """
9
+
10
+ import json
11
+ import logging
12
+ import os
13
+ from collections import deque
14
+ from threading import Lock
15
+ from config import HISTORY_FILE, HISTORY_DEPTH
16
+ from content.config_manager import config_manager
17
+ from content.syllabus_manager import syllabus_manager
18
+ from content.remote_storage import pull_history_from_gist, push_history_to_gist
19
+
20
+ logger = logging.getLogger(__name__)
21
+ _lock = Lock()
22
+
23
+
24
+ def _load() -> dict:
25
+ serialisable = {}
26
+
27
+ # 1. Try pulling from Remote first (Hugging Face / Gist)
28
+ remote_data = pull_history_from_gist()
29
+ if remote_data:
30
+ serialisable = remote_data
31
+
32
+ # 2. Otherwise try Local
33
+ elif os.path.exists(HISTORY_FILE):
34
+ try:
35
+ with open(HISTORY_FILE, "r") as f:
36
+ serialisable = json.load(f)
37
+ except Exception as e:
38
+ logger.error(f"Local history load error: {e}")
39
+ return {}
40
+ else:
41
+ return {}
42
+
43
+ try:
44
+ # Convert lists back to deques with maxlen
45
+ result = {}
46
+ for ch in serialisable:
47
+ if ch == "weekly_archive":
48
+ continue
49
+ result[ch] = {}
50
+ for ct in serialisable[ch]:
51
+ result[ch][ct] = {}
52
+ for subj, items in serialisable[ch][ct].items():
53
+ result[ch][ct][subj] = deque(items, maxlen=HISTORY_DEPTH)
54
+
55
+ # Load weekly archive separately
56
+ result["weekly_archive"] = serialisable.get("weekly_archive", {})
57
+
58
+ return result
59
+ except Exception as e:
60
+ logger.error(f"History load error: {e}")
61
+ return {}
62
+
63
+
64
+ def _save(history: dict):
65
+ try:
66
+ os.makedirs(os.path.dirname(HISTORY_FILE), exist_ok=True)
67
+ serialisable = {}
68
+ for ch in history:
69
+ if ch == "weekly_archive":
70
+ continue
71
+ serialisable[ch] = {}
72
+ for ct in history[ch]:
73
+ serialisable[ch][ct] = {}
74
+ for subj, dq in history[ch][ct].items():
75
+ serialisable[ch][ct][subj] = list(dq)
76
+
77
+ serialisable["weekly_archive"] = history.get("weekly_archive", {})
78
+
79
+ # 1. Save Local
80
+ with open(HISTORY_FILE, "w") as f:
81
+ json.dump(serialisable, f, indent=2)
82
+
83
+ # 2. Push to Remote (Gist)
84
+ push_history_to_gist(serialisable)
85
+
86
+ except Exception as e:
87
+ logger.error(f"History save error: {e}")
88
+
89
+
90
+ # Module-level cache β€” loaded once, written on every update
91
+ _history = _load()
92
+
93
+
94
+ def pick_fresh_chapter(channel_key: str, content_type: str, subject: str) -> str:
95
+ """
96
+ Pick a chapter from the official syllabus that hasn't been recently used
97
+ for this (channel Γ— content_type Γ— subject) combination.
98
+ """
99
+ with _lock:
100
+ # Determine the exam focus for this channel
101
+ channel_cfg = config_manager.channels.get(channel_key, {})
102
+ exam_focus = channel_cfg.get("exam_focus", ["JEE Main"])
103
+
104
+ # Get flattened chapters for this focus + subject
105
+ all_chapters = syllabus_manager.get_chapters(exam_focus, subject)
106
+
107
+ if not all_chapters:
108
+ return "General"
109
+
110
+ used = (
111
+ _history
112
+ .get(channel_key, {})
113
+ .get(content_type, {})
114
+ .get(subject, deque(maxlen=HISTORY_DEPTH))
115
+ )
116
+ used_set = set(used)
117
+
118
+ # Prefer chapters never used
119
+ fresh = [c for c in all_chapters if c not in used_set]
120
+
121
+ if fresh:
122
+ import random
123
+ chapter = random.choice(fresh)
124
+ else:
125
+ # All chapters used β€” pick the one used longest ago (front of deque)
126
+ oldest_used = list(used)
127
+ # Pick from oldest half
128
+ oldest_half = oldest_used[:max(1, len(oldest_used) // 2)]
129
+ import random
130
+ chapter = random.choice(oldest_half)
131
+ logger.info(f"All chapters used for {channel_key}/{content_type}/{subject}, recycling oldest: {chapter}")
132
+
133
+ # Record this pick
134
+ _history \
135
+ .setdefault(channel_key, {}) \
136
+ .setdefault(content_type, {}) \
137
+ .setdefault(subject, deque(maxlen=HISTORY_DEPTH)) \
138
+ .append(chapter)
139
+
140
+ _save(_history)
141
+ return chapter
142
+
143
+
144
+ def get_channel_history_summary(channel_key: str) -> dict:
145
+ """Return a summary of how many unique chapters have been covered per subject."""
146
+ ch_data = _history.get(channel_key, {})
147
+ summary = {}
148
+ for content_type, subjects in ch_data.items():
149
+ summary[content_type] = {
150
+ subj: list(chapters)
151
+ for subj, chapters in subjects.items()
152
+ }
153
+ return summary
154
+
155
+
156
+ def clear_channel_history(channel_key: str):
157
+ """Reset history for a specific channel (admin action)."""
158
+ with _lock:
159
+ if channel_key in _history:
160
+ del _history[channel_key]
161
+ _save(_history)
162
+ logger.info(f"Cleared history for channel: {channel_key}")
163
+
164
+
165
+ def get_coverage_stats() -> dict:
166
+ """
167
+ Returns per-channel coverage stats.
168
+ """
169
+ stats = {}
170
+ for ch_key, ch_data in _history.items():
171
+ if ch_key == "weekly_archive": continue
172
+ channel_cfg = config_manager.channels.get(ch_key, {})
173
+ exam_focus = channel_cfg.get("exam_focus", ["JEE Main"])
174
+
175
+ stats[ch_key] = {}
176
+ for ct, subjects in ch_data.items():
177
+ covered = sum(len(set(list(chapters))) for chapters in subjects.values())
178
+ total = sum(len(syllabus_manager.get_chapters(exam_focus, s)) for s in subjects)
179
+ stats[ch_key][ct] = {
180
+ "covered": covered,
181
+ "total": total,
182
+ "pct": round(covered / total * 100, 1) if total else 0,
183
+ }
184
+ return stats
185
+
186
+
187
+ def get_channel_stats(channel_key: str) -> dict:
188
+ """Detailed stats for ONE channel, grouped by Subject."""
189
+ # Determine exam focus
190
+ channel_cfg = config_manager.channels.get(channel_key, {})
191
+ exam_focus = channel_cfg.get("exam_focus", ["JEE Main"])
192
+
193
+ # FIX: initialise ch_data and stats before using them
194
+ ch_data = _history.get(channel_key, {})
195
+ stats = {}
196
+
197
+ # Combine all content types for a total subject view
198
+ for ct, subjects in ch_data.items():
199
+ for subj, chapters in subjects.items():
200
+ if subj not in stats:
201
+ total_chapters = len(syllabus_manager.get_chapters(exam_focus, subj))
202
+ stats[subj] = {"covered": set(), "total": total_chapters}
203
+ stats[subj]["covered"].update(list(chapters))
204
+
205
+ # Calculate final percentages
206
+ result = {}
207
+ for subj, data in stats.items():
208
+ covered_count = len(data["covered"])
209
+ total_count = data["total"]
210
+ result[subj] = {
211
+ "covered": covered_count,
212
+ "total": total_count,
213
+ "pct": round(covered_count / total_count * 100, 1) if total_count else 0
214
+ }
215
+ return result
216
+
217
+
218
+ # ─────────────────────────────────────────────
219
+ # Weekly Archive Helpers (for PDF Digest)
220
+ # ─────────────────────────────────────────────
221
+
222
+ def archive_weekly_post(channel_key: str, content_type: str, subject: str, chapter: str, text: str):
223
+ """Save the full text of a post for the Sunday PDF compilation."""
224
+ with _lock:
225
+ archive = _history.setdefault("weekly_archive", {})
226
+ ch_archive = archive.setdefault(channel_key, {})
227
+ ct_archive = ch_archive.setdefault(content_type, [])
228
+
229
+ # Append as a structured entry
230
+ from datetime import datetime as _dt
231
+ ct_archive.append({
232
+ "subject": subject,
233
+ "chapter": chapter,
234
+ "text": text,
235
+ "date": _dt.now().strftime("%d %b %Y") # actual date, not env var
236
+ })
237
+ _save(_history)
238
+ logger.info(f"Archived [{content_type}] for {channel_key} weekly digest.")
239
+
240
+
241
+ def get_weekly_archive(channel_key: str, content_type: str) -> list:
242
+ """Retrieve the week's archived posts for a channel and type."""
243
+ return _history.get("weekly_archive", {}).get(channel_key, {}).get(content_type, [])
244
+
245
+
246
+ def clear_weekly_archive(channel_key: str = None):
247
+ """Clear the weekly archive after the PDF is posted."""
248
+ with _lock:
249
+ if "weekly_archive" in _history:
250
+ if channel_key:
251
+ if channel_key in _history["weekly_archive"]:
252
+ _history["weekly_archive"][channel_key] = {}
253
+ else:
254
+ _history["weekly_archive"] = {}
255
+ _save(_history)
256
+ logger.info(f"Cleared weekly archive {f'for {channel_key}' if channel_key else 'completely'}.")
content/news_scraper.py CHANGED
@@ -1,115 +1,115 @@
1
- import requests
2
- import re
3
- import logging
4
- from content.database import is_news_seen, mark_news_seen
5
-
6
- logger = logging.getLogger(__name__)
7
-
8
- # Target: NTA Main Page (contains "Latest @ NTA" section)
9
- NTA_URL = "https://www.nta.ac.in/"
10
-
11
- def scrape_nta_news():
12
- """
13
- Scrape the NTA website for the latest 5 announcements.
14
- Returns a list of dicts: [{'title': str, 'link': str, 'hash': str}]
15
- """
16
- try:
17
- # Using a browser-like User-Agent to avoid getting blocked
18
- headers = {
19
- "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36"
20
- }
21
- resp = requests.get(NTA_URL, headers=headers, timeout=15)
22
- if resp.status_code != 200:
23
- logger.error(f"NTA Scrape Failed (Status {resp.status_code})")
24
- return []
25
-
26
- html = resp.text
27
-
28
- # We are looking for news items in the list.
29
- # NTA usually uses <a> tags inside <li> or <div> for news.
30
- # Regex to find links starting with /Download/Notice/ or containing .pdf
31
- # Example: <a href="/Download/Notice/Notice_202405101234.pdf" target="_blank">Title here</a>
32
-
33
- # This regex finds the href and the link text
34
- matches = re.findall(r'<a[^>]+href="([^"]+)"[^>]*>(.*?)</a>', html, re.DOTALL)
35
-
36
- news_items = []
37
- import html as html_parser
38
- for href, text in matches:
39
- # Clean up the text (remove tags, unescape html entities, normalize whitespace)
40
- clean_text = re.sub(r'<[^>]+>', '', text)
41
- title = html_parser.unescape(clean_text)
42
- title = re.sub(r'\s+', ' ', title).strip()
43
-
44
- if not title or len(title) < 10: continue
45
-
46
- # STRICT FILTER: Only announcements for JEE, NEET, CUET
47
- keywords = ["jee", "neet", "cuet"]
48
- if not any(k in title.lower() for k in keywords):
49
- continue
50
-
51
- # Complete the URL
52
- link = href
53
- if link.startswith("/"):
54
- link = "https://www.nta.ac.in" + link
55
-
56
- # Check if this announcement has been posted before (by title)
57
- if not is_news_seen(title):
58
- news_items.append({
59
- "title": title,
60
- "link": link
61
- })
62
-
63
- # Return all new items found
64
- return news_items
65
-
66
- except Exception as e:
67
- logger.error(f"NTA Scraper Error: {e}")
68
- return []
69
-
70
- def get_news_message(item):
71
- """Format a single news item for Telegram using HTML formatting."""
72
- import html as html_parser
73
- title_esc = html_parser.escape(item['title'])
74
- return (
75
- f"πŸ”” <b>NEW NTA UPDATE</b>\n\n"
76
- f"πŸ“Œ {title_esc}\n\n"
77
- f"πŸ”— <a href=\"{item['link']}\">Read Official Notice</a>\n\n"
78
- f"πŸš€ <b>CrazyLearners</b> | @xCrazyLearners"
79
- )
80
-
81
- def get_consolidated_news_message(news_items):
82
- """Format multiple news items into a single consolidated message using HTML formatting."""
83
- if not news_items:
84
- return ""
85
-
86
- import html as html_parser
87
- if len(news_items) == 1:
88
- item = news_items[0]
89
- title_esc = html_parser.escape(item['title'])
90
- return (
91
- f"πŸ”” <b>NEW NTA UPDATE</b>\n\n"
92
- f"πŸ“Œ <b>{title_esc}</b>\n\n"
93
- f"πŸ“– <b>Instruction:</b> Click the link below to view the official PDF notice.\n\n"
94
- f"πŸ”— <a href=\"{item['link']}\">Read Official Notice (PDF)</a>\n\n"
95
- f"πŸš€ <b>CrazyLearners</b> | @xCrazyLearners"
96
- )
97
-
98
- text = "πŸ”” <b>NEW NTA ANNOUNCEMENTS</b>\n"
99
- text += "━━━━━━━━━━━━━━━━━━━━━━\n\n"
100
- text += "πŸ“’ <b>Latest Updates for JEE | NEET | CUET</b>\n\n"
101
-
102
- for i, item in enumerate(news_items, 1):
103
- num = f"{i}️⃣" if i <= 10 else f"{i}."
104
- title_esc = html_parser.escape(item['title'])
105
- text += f"{num} <b>{title_esc}</b>\n"
106
- text += f" πŸ”— <a href=\"{item['link']}\">View Official Notice</a>\n\n"
107
-
108
- text += "━━━━━━━━━━━━━━━━━━━━━━\n"
109
- text += "πŸš€ <b>@xCrazyLearners</b> | Your one-stop exam guide\n"
110
- text += "<code>Never miss an important announcement</code>\n\n"
111
- text += "πŸ‘ <b>React to appreciate</b>\n"
112
- text += "πŸ’¬ <b>Share with friends preparing for exams</b>\n"
113
- text += "πŸ”” <b>Enable notifications for live updates</b>\n"
114
- text += "πŸ“Œ <b>Save this for future reference</b>"
115
- return text
 
1
+ import requests
2
+ import re
3
+ import logging
4
+ from content.database import is_news_seen, mark_news_seen
5
+
6
+ logger = logging.getLogger(__name__)
7
+
8
+ # Target: NTA Main Page (contains "Latest @ NTA" section)
9
+ NTA_URL = "https://www.nta.ac.in/"
10
+
11
+ def scrape_nta_news():
12
+ """
13
+ Scrape the NTA website for the latest 5 announcements.
14
+ Returns a list of dicts: [{'title': str, 'link': str, 'hash': str}]
15
+ """
16
+ try:
17
+ # Using a browser-like User-Agent to avoid getting blocked
18
+ headers = {
19
+ "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36"
20
+ }
21
+ resp = requests.get(NTA_URL, headers=headers, timeout=15)
22
+ if resp.status_code != 200:
23
+ logger.error(f"NTA Scrape Failed (Status {resp.status_code})")
24
+ return []
25
+
26
+ html = resp.text
27
+
28
+ # We are looking for news items in the list.
29
+ # NTA usually uses <a> tags inside <li> or <div> for news.
30
+ # Regex to find links starting with /Download/Notice/ or containing .pdf
31
+ # Example: <a href="/Download/Notice/Notice_202405101234.pdf" target="_blank">Title here</a>
32
+
33
+ # This regex finds the href and the link text
34
+ matches = re.findall(r'<a[^>]+href="([^"]+)"[^>]*>(.*?)</a>', html, re.DOTALL)
35
+
36
+ news_items = []
37
+ import html as html_parser
38
+ for href, text in matches:
39
+ # Clean up the text (remove tags, unescape html entities, normalize whitespace)
40
+ clean_text = re.sub(r'<[^>]+>', '', text)
41
+ title = html_parser.unescape(clean_text)
42
+ title = re.sub(r'\s+', ' ', title).strip()
43
+
44
+ if not title or len(title) < 10: continue
45
+
46
+ # STRICT FILTER: Only announcements for JEE, NEET, CUET
47
+ keywords = ["jee", "neet", "cuet"]
48
+ if not any(k in title.lower() for k in keywords):
49
+ continue
50
+
51
+ # Complete the URL
52
+ link = href
53
+ if link.startswith("/"):
54
+ link = "https://www.nta.ac.in" + link
55
+
56
+ # Check if this announcement has been posted before (by title)
57
+ if not is_news_seen(title):
58
+ news_items.append({
59
+ "title": title,
60
+ "link": link
61
+ })
62
+
63
+ # Return all new items found
64
+ return news_items
65
+
66
+ except Exception as e:
67
+ logger.error(f"NTA Scraper Error: {e}")
68
+ return []
69
+
70
+ def get_news_message(item):
71
+ """Format a single news item for Telegram using HTML formatting."""
72
+ import html as html_parser
73
+ title_esc = html_parser.escape(item['title'])
74
+ return (
75
+ f"πŸ”” <b>NEW NTA UPDATE</b>\n\n"
76
+ f"πŸ“Œ {title_esc}\n\n"
77
+ f"πŸ”— <a href=\"{item['link']}\">Read Official Notice</a>\n\n"
78
+ f"πŸš€ <b>CrazyLearners</b> | @xCrazyLearners"
79
+ )
80
+
81
+ def get_consolidated_news_message(news_items):
82
+ """Format multiple news items into a single consolidated message using HTML formatting."""
83
+ if not news_items:
84
+ return ""
85
+
86
+ import html as html_parser
87
+ if len(news_items) == 1:
88
+ item = news_items[0]
89
+ title_esc = html_parser.escape(item['title'])
90
+ return (
91
+ f"πŸ”” <b>NEW NTA UPDATE</b>\n\n"
92
+ f"πŸ“Œ <b>{title_esc}</b>\n\n"
93
+ f"πŸ“– <b>Instruction:</b> Click the link below to view the official PDF notice.\n\n"
94
+ f"πŸ”— <a href=\"{item['link']}\">Read Official Notice (PDF)</a>\n\n"
95
+ f"πŸš€ <b>CrazyLearners</b> | @xCrazyLearners"
96
+ )
97
+
98
+ text = "πŸ”” <b>NEW NTA ANNOUNCEMENTS</b>\n"
99
+ text += "━━━━━━━━━━━━━━━━━━━━━━\n\n"
100
+ text += "πŸ“’ <b>Latest Updates for JEE | NEET | CUET</b>\n\n"
101
+
102
+ for i, item in enumerate(news_items, 1):
103
+ num = f"{i}️⃣" if i <= 10 else f"{i}."
104
+ title_esc = html_parser.escape(item['title'])
105
+ text += f"{num} <b>{title_esc}</b>\n"
106
+ text += f" πŸ”— <a href=\"{item['link']}\">View Official Notice</a>\n\n"
107
+
108
+ text += "━━━━━━━━━━━━━━━━━━━━━━\n"
109
+ text += "πŸš€ <b>@xCrazyLearners</b> | Your one-stop exam guide\n"
110
+ text += "<code>Never miss an important announcement</code>\n\n"
111
+ text += "πŸ‘ <b>React to appreciate</b>\n"
112
+ text += "πŸ’¬ <b>Share with friends preparing for exams</b>\n"
113
+ text += "πŸ”” <b>Enable notifications for live updates</b>\n"
114
+ text += "πŸ“Œ <b>Save this for future reference</b>"
115
+ return text
content/pdf_generator.py CHANGED
@@ -1,551 +1,551 @@
1
- """
2
- pdf_generator.py β€” Branded Weekly Digest PDF Generator
3
- CrazyLearners | t.me/xcrazylearners
4
-
5
- Layout (LaTeX-inspired with fpdf2):
6
- β€’ Cover page β€” title, channel name, date, branding banner
7
- β€’ TOC page β€” list of subjects + chapters
8
- β€’ Content β€” Subject divider β†’ Chapter card β†’ body text (justified)
9
- β€’ Every page β€” header with logo-text + footer with page no. + channel link
10
- β€’ Last page β€” CrazyLearners branding / call-to-action
11
-
12
- Fonts used (built-in fpdf2, no external download needed):
13
- Helvetica β€” sans-serif (headings, UI chrome)
14
- Courier β€” monospace (formula blocks)
15
- """
16
-
17
- import os
18
- import re
19
- import logging
20
- from datetime import datetime
21
- from fpdf import FPDF
22
-
23
- logger = logging.getLogger(__name__)
24
-
25
- # ─── Brand constants ────────────────────────────────────────────────────────────
26
- BRAND_NAME = "CrazyLearners"
27
- BRAND_HANDLE = "@xcrazylearners"
28
- BRAND_LINK = "t.me/xcrazylearners"
29
- BRAND_TAGLINE = "Learn Smarter. Score Higher."
30
-
31
- # Colour palette (R, G, B)
32
- C_BRAND_DARK = (15, 23, 42) # near-black navy β€” cover bg simulation (border)
33
- C_BRAND_PURPLE = (79, 70, 229) # indigo-600 β€” primary accent
34
- C_BRAND_TEAL = (20, 184, 166) # teal-500 β€” secondary accent
35
- C_SECTION_RED = (220, 38, 38) # red-600 β€” subject headings
36
- C_CHAPTER_BLU = (37, 99, 235) # blue-600 β€” chapter headings
37
- C_BODY = (30, 30, 30) # near-black β€” body text
38
- C_LIGHT_GREY = (200, 200, 200) # divider lines
39
- C_WHITE = (255, 255, 255)
40
- C_MID_GREY = (120, 120, 120) # captions / footnotes
41
- C_GOLD = (217, 119, 6) # amber-600 β€” highlight boxes
42
-
43
-
44
- # ─── Text helpers ────────────────────────────────────────────────────────────────
45
-
46
- def _strip_markdown(text: str) -> str:
47
- """Remove Markdown markers but preserve structure."""
48
- if not text:
49
- return ""
50
- # Bold / Italic markers
51
- text = re.sub(r'\*{1,3}(.*?)\*{1,3}', r'\1', text, flags=re.DOTALL)
52
- text = re.sub(r'_{1,2}(.*?)_{1,2}', r'\1', text, flags=re.DOTALL)
53
- # Inline code β†’ keep content, drop backticks
54
- text = re.sub(r'`([^`]*)`', r'\1', text)
55
- # Fenced code blocks β€” keep content
56
- text = re.sub(r'```(?:\w+)?\n(.*?)```', r'\1', text, flags=re.DOTALL)
57
- # Decorative separator lines (━━━ etc.)
58
- text = re.sub(r'[━─=]{3,}', '---', text)
59
- # Hashtags
60
- text = re.sub(r'#\w+', '', text)
61
- # Footer / brand lines already embedded in posts (we'll add our own)
62
- text = re.sub(r'(CrazyLearners|xcrazylearners|t\.me/)', '', text, flags=re.I)
63
- return text.strip()
64
-
65
-
66
- def _safe_latin1(text: str) -> str:
67
- """
68
- fpdf2's built-in fonts (Helvetica/Courier) only support Latin-1.
69
- Map common Unicode symbols to ASCII equivalents; drop the rest.
70
- """
71
- replacements = {
72
- '\u2192': '->', '\u2190': '<-', '\u2194': '<->',
73
- '\u2260': '!=', '\u2248': '~=', '\u2265': '>=',
74
- '\u2264': '<=', '\u00b1': '+/-', '\u00d7': 'x',
75
- '\u00f7': '/', '\u03b1': 'alpha', '\u03b2': 'beta',
76
- '\u03b3': 'gamma', '\u03b4': 'delta', '\u03c0': 'pi',
77
- '\u03bb': 'lambda', '\u03bc': 'mu', '\u03c3': 'sigma',
78
- '\u03c9': 'omega', '\u00b2': '^2', '\u00b3': '^3',
79
- '\u221a': 'sqrt', '\u221e': 'inf', '\u2211': 'sum',
80
- '\u222b': 'int', '\u2202': 'd', '\u0394': 'Delta',
81
- '\u03a9': 'Omega', '\u2019': "'", '\u2018': "'",
82
- '\u201c': '"', '\u201d': '"',
83
- '\u2022': '-', '\u2023': '>', '\u25cf': '*',
84
- '\u2713': '[OK]', '\u2714': '[OK]', '\u2718': '[X]',
85
- # Emojis β€” strip completely (map to empty string or label)
86
- '\U0001f4da': '[BOOK]', '\U0001f4dd': '[NOTE]',
87
- '\U0001f4a1': '[TIP]', '\U0001f3af': '[TARGET]',
88
- '\U0001f525': '[FIRE]', '\U0001f9e0': '[BRAIN]',
89
- '\U00002705': '[OK]', '\U0000274c': '[X]',
90
- '\U000026a0': '[WARN]',
91
- }
92
- for uni, asc in replacements.items():
93
- text = text.replace(uni, asc)
94
- # Drop any remaining non-latin1 characters
95
- text = text.encode('latin-1', errors='ignore').decode('latin-1')
96
- # Collapse excessive blank lines
97
- text = re.sub(r'\n{3,}', '\n\n', text)
98
- return text.strip()
99
-
100
-
101
- def _clean(text: str) -> str:
102
- """Full pipeline: strip markdown β†’ safe latin-1."""
103
- return _safe_latin1(_strip_markdown(text))
104
-
105
-
106
- # ─── PDF Class ───────────────────────────────────────────────────────────────────
107
-
108
- class BrandedPDF(FPDF):
109
- """
110
- CrazyLearners branded PDF with LaTeX-inspired layout.
111
- Each page has a top header bar and a bottom footer bar.
112
- """
113
-
114
- def __init__(self, channel_label: str, content_type_label: str):
115
- super().__init__(orientation='P', unit='mm', format='A4')
116
- self.channel_label = _safe_latin1(channel_label)
117
- self.content_type_label = _safe_latin1(content_type_label)
118
- self.set_margins(left=18, top=28, right=18)
119
- self.set_auto_page_break(auto=True, margin=22)
120
-
121
- # ── Header (auto-called on every new page except cover) ──────────────────
122
- def header(self):
123
- if self.page == 1:
124
- return # cover page handles its own layout
125
-
126
- # Top rule
127
- self.set_draw_color(*C_BRAND_PURPLE)
128
- self.set_line_width(0.8)
129
- self.line(10, 10, 200, 10)
130
-
131
- # Brand name (left)
132
- self.set_xy(10, 12)
133
- self.set_font('Helvetica', 'B', 9)
134
- self.set_text_color(*C_BRAND_PURPLE)
135
- self.cell(80, 6, BRAND_NAME.upper(), align='L')
136
-
137
- # Channel label (right)
138
- self.set_xy(110, 12)
139
- self.set_font('Helvetica', '', 8)
140
- self.set_text_color(*C_MID_GREY)
141
- self.cell(80, 6, self.channel_label, align='R')
142
-
143
- self.ln(4)
144
-
145
- # ── Footer ───────────────────────────────────────────────────────────────
146
- def footer(self):
147
- if self.page == 1:
148
- return
149
-
150
- self.set_y(-14)
151
- self.set_draw_color(*C_LIGHT_GREY)
152
- self.set_line_width(0.3)
153
- self.line(10, self.get_y(), 200, self.get_y())
154
- self.ln(1)
155
-
156
- self.set_font('Helvetica', 'I', 7.5)
157
- self.set_text_color(*C_MID_GREY)
158
-
159
- # Left: page number
160
- self.set_x(10)
161
- self.cell(60, 5, f'Page {self.page_no()}', align='L')
162
-
163
- # Centre: content type
164
- self.set_x(70)
165
- self.cell(60, 5, self.content_type_label, align='C')
166
-
167
- # Right: channel link
168
- self.set_x(130)
169
- self.cell(60, 5, BRAND_LINK, align='R')
170
-
171
- # ── Helpers ───────────────────────────────────────────────────────────────
172
-
173
- def _hline(self, color=C_LIGHT_GREY, width=0.3, lm=18, rm=192):
174
- self.set_draw_color(*color)
175
- self.set_line_width(width)
176
- self.line(lm, self.get_y(), rm, self.get_y())
177
-
178
- def _filled_rect(self, x, y, w, h, fill_color, radius=2.0):
179
- """Draw a filled rounded rectangle (section card background)."""
180
- self.set_fill_color(*fill_color)
181
- self.set_draw_color(*fill_color)
182
- self.rounded_rect(x, y, w, h, radius, style='F')
183
-
184
- def _section_pill(self, label: str):
185
- """Draw a coloured pill/badge for the subject label."""
186
- pill_w = 50
187
- pill_h = 8
188
- pill_x = self.l_margin
189
- pill_y = self.get_y()
190
- self._filled_rect(pill_x, pill_y, pill_w, pill_h,
191
- fill_color=C_BRAND_PURPLE)
192
- self.set_xy(pill_x, pill_y)
193
- self.set_font('Helvetica', 'B', 9)
194
- self.set_text_color(*C_WHITE)
195
- self.cell(pill_w, pill_h, label.upper(), align='C')
196
- self.ln(pill_h + 3)
197
- self.set_text_color(*C_BODY)
198
-
199
- def _chapter_card(self, chapter: str):
200
- """Light teal card behind chapter heading."""
201
- card_x = self.l_margin
202
- card_y = self.get_y()
203
- card_w = self.epw # effective page width
204
- card_h = 9
205
- # Light teal fill
206
- self.set_fill_color(230, 255, 252)
207
- self.set_draw_color(*C_BRAND_TEAL)
208
- self.set_line_width(0.4)
209
- self.rounded_rect(card_x, card_y, card_w, card_h, 2, style='FD')
210
-
211
- self.set_xy(card_x + 3, card_y + 1.5)
212
- self.set_font('Helvetica', 'B', 10)
213
- self.set_text_color(*C_CHAPTER_BLU)
214
- self.cell(card_w - 6, 6, f' Chapter: {_safe_latin1(chapter)}')
215
- self.ln(card_h + 2)
216
- self.set_text_color(*C_BODY)
217
-
218
- def _body_text(self, text: str):
219
- """
220
- Render body text with LaTeX-like paragraph handling.
221
- Lines starting with '-', '*', or a number followed by '.' are bullet points.
222
- Lines with ALL CAPS or ending with ':' are treated as sub-headings.
223
- """
224
- paragraphs = text.split('\n')
225
- self.set_font('Helvetica', '', 9.5)
226
- self.set_text_color(*C_BODY)
227
-
228
- for para in paragraphs:
229
- para = para.strip()
230
- if not para:
231
- self.ln(2.5)
232
- continue
233
-
234
- # Horizontal rule placeholder
235
- if para.startswith('---'):
236
- self._hline(C_LIGHT_GREY, 0.2)
237
- self.ln(2)
238
- continue
239
-
240
- # Sub-heading detection: ends with ':' or ALL-CAPS short line
241
- is_subhead = (
242
- (para.endswith(':') and len(para) < 80) or
243
- (para.isupper() and len(para) < 60)
244
- )
245
- if is_subhead:
246
- self.ln(1)
247
- self.set_font('Helvetica', 'B', 9.5)
248
- self.set_text_color(*C_BRAND_PURPLE)
249
- self.multi_cell(0, 5.5, para, align='L')
250
- self.set_font('Helvetica', '', 9.5)
251
- self.set_text_color(*C_BODY)
252
- self.ln(0.5)
253
- continue
254
-
255
- # Bullet points
256
- if re.match(r'^[-*\u2022]\s+', para):
257
- bullet_text = re.sub(r'^[-*\u2022]\s+', '', para)
258
- self.set_x(self.l_margin + 5)
259
- self.set_font('Helvetica', '', 9.5)
260
- self.cell(4, 5.5, '-')
261
- self.multi_cell(self.epw - 9, 5.5, _safe_latin1(bullet_text), align='L')
262
- continue
263
-
264
- # Numbered list
265
- if re.match(r'^\d+[.)]\s+', para):
266
- self.set_x(self.l_margin + 2)
267
- self.multi_cell(0, 5.5, _safe_latin1(para), align='L')
268
- continue
269
-
270
- # Normal paragraph β€” justified
271
- self.multi_cell(0, 5.5, _safe_latin1(para), align='J')
272
- self.ln(1)
273
-
274
-
275
- # ─── Cover Page ─────────────────────────────────────────────────────────────────
276
-
277
- def _draw_cover(pdf: BrandedPDF, channel_name: str,
278
- content_type_label: str, week_range: str):
279
- """
280
- Draw a premium-looking cover page:
281
- top accent bar | title block | meta block | branding block
282
- """
283
- A4_W, A4_H = 210, 297
284
-
285
- # ── Top accent bar (full width) ──
286
- pdf.set_fill_color(*C_BRAND_PURPLE)
287
- pdf.rect(0, 0, A4_W, 18, style='F')
288
-
289
- # Brand name in the bar
290
- pdf.set_xy(0, 4)
291
- pdf.set_font('Helvetica', 'B', 11)
292
- pdf.set_text_color(*C_WHITE)
293
- pdf.cell(A4_W, 10, BRAND_NAME.upper() + ' | ' + BRAND_HANDLE, align='C')
294
-
295
- # ── Second teal stripe ──
296
- pdf.set_fill_color(*C_BRAND_TEAL)
297
- pdf.rect(0, 18, A4_W, 4, style='F')
298
-
299
- # ── Central title block ──
300
- pdf.set_xy(20, 65)
301
- pdf.set_font('Helvetica', 'B', 28)
302
- pdf.set_text_color(*C_BRAND_DARK)
303
- pdf.multi_cell(170, 14, _safe_latin1(content_type_label).upper(), align='C')
304
-
305
- # Underline the title
306
- title_y = pdf.get_y() + 2
307
- pdf.set_draw_color(*C_BRAND_PURPLE)
308
- pdf.set_line_width(1.2)
309
- pdf.line(45, title_y, 165, title_y)
310
- pdf.ln(10)
311
-
312
- # Channel name
313
- pdf.set_font('Helvetica', 'B', 16)
314
- pdf.set_text_color(*C_BRAND_PURPLE)
315
- pdf.cell(0, 12, _safe_latin1(channel_name), align='C', new_x='LMARGIN', new_y='NEXT')
316
-
317
- # Week range
318
- pdf.set_font('Helvetica', '', 12)
319
- pdf.set_text_color(*C_MID_GREY)
320
- pdf.cell(0, 8, week_range, align='C', new_x='LMARGIN', new_y='NEXT')
321
- pdf.ln(6)
322
-
323
- # Tagline
324
- pdf.set_font('Helvetica', 'I', 12)
325
- pdf.set_text_color(*C_GOLD)
326
- pdf.cell(0, 8, BRAND_TAGLINE, align='C', new_x='LMARGIN', new_y='NEXT')
327
- pdf.ln(40)
328
-
329
- # ── Bottom branding box ──
330
- box_y = A4_H - 70
331
- pdf.set_fill_color(245, 245, 255)
332
- pdf.set_draw_color(*C_BRAND_PURPLE)
333
- pdf.set_line_width(0.5)
334
- pdf.rounded_rect(20, box_y, A4_W - 40, 45, 4, style='FD')
335
-
336
- pdf.set_xy(20, box_y + 6)
337
- pdf.set_font('Helvetica', 'B', 11)
338
- pdf.set_text_color(*C_BRAND_PURPLE)
339
- pdf.cell(A4_W - 40, 8, 'JOIN OUR COMMUNITY', align='C', new_x='LMARGIN', new_y='NEXT')
340
-
341
- pdf.set_x(20)
342
- pdf.set_font('Helvetica', '', 10)
343
- pdf.set_text_color(*C_BODY)
344
- pdf.cell(A4_W - 40, 7,
345
- 'Daily Notes | Formula Sheets | PYQ Sessions | MCQ Polls',
346
- align='C', new_x='LMARGIN', new_y='NEXT')
347
-
348
- pdf.set_x(20)
349
- pdf.set_font('Helvetica', 'B', 12)
350
- pdf.set_text_color(*C_BRAND_TEAL)
351
- pdf.cell(A4_W - 40, 9, BRAND_LINK, align='C', new_x='LMARGIN', new_y='NEXT')
352
-
353
- pdf.set_x(20)
354
- pdf.set_font('Helvetica', '', 9)
355
- pdf.set_text_color(*C_MID_GREY)
356
- pdf.cell(A4_W - 40, 7,
357
- f'Generated: {datetime.now().strftime("%d %b %Y, %I:%M %p IST")}',
358
- align='C')
359
-
360
- # ── Bottom stripe ──
361
- pdf.set_fill_color(*C_BRAND_TEAL)
362
- pdf.rect(0, A4_H - 12, A4_W, 12, style='F')
363
- pdf.set_xy(0, A4_H - 10)
364
- pdf.set_font('Helvetica', 'I', 8)
365
- pdf.set_text_color(*C_WHITE)
366
- pdf.cell(A4_W, 8, 'Free for personal use. Share freely!', align='C')
367
-
368
-
369
- # ─── Table of Contents ───────────────────────────────────────────────────────────
370
-
371
- def _draw_toc(pdf: BrandedPDF, grouped: dict):
372
- pdf.add_page()
373
- pdf.set_font('Helvetica', 'B', 16)
374
- pdf.set_text_color(*C_BRAND_PURPLE)
375
- pdf.cell(0, 12, 'TABLE OF CONTENTS', new_x='LMARGIN', new_y='NEXT', align='C')
376
- pdf.set_draw_color(*C_BRAND_PURPLE)
377
- pdf.set_line_width(0.6)
378
- pdf.line(18, pdf.get_y(), 192, pdf.get_y())
379
- pdf.ln(6)
380
-
381
- entry_num = 1
382
- for subj, chapters in grouped.items():
383
- pdf.set_font('Helvetica', 'B', 11)
384
- pdf.set_text_color(*C_SECTION_RED)
385
- pdf.cell(0, 8, f'{subj}', new_x='LMARGIN', new_y='NEXT')
386
-
387
- pdf.set_font('Helvetica', '', 10)
388
- pdf.set_text_color(*C_BODY)
389
- for chap in chapters.keys():
390
- safe_chap = _safe_latin1(chap)
391
- # Dot leader
392
- pdf.set_x(pdf.l_margin + 6)
393
- pdf.cell(4, 6.5, str(entry_num) + '.')
394
- pdf.cell(130, 6.5, safe_chap[:65])
395
- entry_num += 1
396
- pdf.ln(6.5)
397
- pdf.ln(2)
398
-
399
-
400
- # ─── Back / CTA page ─────────────────────────────────────────────────────────────
401
-
402
- def _draw_back_page(pdf: BrandedPDF):
403
- pdf.add_page()
404
- A4_W = 210
405
-
406
- pdf.ln(30)
407
- pdf.set_font('Helvetica', 'B', 22)
408
- pdf.set_text_color(*C_BRAND_PURPLE)
409
- pdf.cell(0, 14, 'Keep Learning, Keep Growing!', align='C', new_x='LMARGIN', new_y='NEXT')
410
-
411
- pdf.set_font('Helvetica', 'I', 13)
412
- pdf.set_text_color(*C_MID_GREY)
413
- pdf.cell(0, 9, BRAND_TAGLINE, align='C', new_x='LMARGIN', new_y='NEXT')
414
- pdf.ln(20)
415
-
416
- # Info box
417
- box_y = pdf.get_y()
418
- pdf.set_fill_color(240, 240, 255)
419
- pdf.set_draw_color(*C_BRAND_PURPLE)
420
- pdf.set_line_width(0.5)
421
- pdf.rounded_rect(25, box_y, A4_W - 50, 80, 5, style='FD')
422
-
423
- pdf.set_xy(25, box_y + 10)
424
- pdf.set_font('Helvetica', 'B', 13)
425
- pdf.set_text_color(*C_BRAND_PURPLE)
426
- pdf.cell(A4_W - 50, 10, 'What we offer daily:', align='C', new_x='LMARGIN', new_y='NEXT')
427
-
428
- items = [
429
- '[NOTE] Short Notes & Formula Sheets',
430
- '[TARGET] PYQ Questions with Solutions',
431
- '[BRAIN] Memory Tricks & Mnemonics',
432
- '[FIRE] MCQ Poll Sessions (10 Questions)',
433
- '[TIP] Concept Recaps & Mock Questions',
434
- ]
435
- pdf.set_font('Helvetica', '', 11)
436
- pdf.set_text_color(*C_BODY)
437
- for item in items:
438
- pdf.set_x(35)
439
- pdf.cell(A4_W - 70, 9, item, new_x='LMARGIN', new_y='NEXT')
440
-
441
- pdf.ln(25)
442
- pdf.set_font('Helvetica', 'B', 16)
443
- pdf.set_text_color(*C_BRAND_TEAL)
444
- pdf.cell(0, 12, BRAND_LINK, align='C', new_x='LMARGIN', new_y='NEXT')
445
-
446
- pdf.set_font('Helvetica', '', 10)
447
- pdf.set_text_color(*C_MID_GREY)
448
- pdf.cell(0, 8, 'Tap the link in Telegram to join!', align='C')
449
-
450
- # Bottom bar
451
- pdf.set_fill_color(*C_BRAND_PURPLE)
452
- pdf.rect(0, 285, A4_W, 12, style='F')
453
- pdf.set_xy(0, 287)
454
- pdf.set_font('Helvetica', 'I', 8)
455
- pdf.set_text_color(*C_WHITE)
456
- pdf.cell(A4_W, 8, f'{BRAND_NAME} | {BRAND_LINK} | Free to share!', align='C')
457
-
458
-
459
- # ─── Public API ──────────────────────────────────────────────────────────────────
460
-
461
- def create_digest_pdf(channel_name: str, content_type_label: str,
462
- archive_items: list) -> str:
463
- """
464
- Creates a branded, LaTeX-inspired chapter-wise PDF from archived posts.
465
-
466
- Args:
467
- channel_name: Human-readable channel label (e.g. "JEE Advanced Daily")
468
- content_type_label: e.g. "Short Notes" or "Formula Sheet"
469
- archive_items: List of dicts: [{subject, chapter, text, date}, ...]
470
-
471
- Returns:
472
- Absolute path to the generated PDF, or None on failure.
473
- """
474
- if not archive_items:
475
- logger.warning("create_digest_pdf called with empty archive_items")
476
- return None
477
-
478
- try:
479
- pdf = BrandedPDF(channel_name, content_type_label)
480
-
481
- # ── Cover page (page 1) ──
482
- pdf.add_page()
483
- now = datetime.now()
484
- week_start = now.strftime("%d %b") # approximate β€” Sunday digest
485
- week_range = f'Week of {week_start} {now.year}'
486
- _draw_cover(pdf, channel_name, f'Weekly {content_type_label}', week_range)
487
-
488
- # ── Group archive by Subject β†’ Chapter ──
489
- grouped: dict = {}
490
- for item in archive_items:
491
- subj = str(item.get('subject', 'General')).title()
492
- chap = str(item.get('chapter', 'General'))
493
- text = str(item.get('text', ''))
494
- grouped.setdefault(subj, {}).setdefault(chap, []).append(text)
495
-
496
- # ── Table of Contents (page 2) ──
497
- _draw_toc(pdf, grouped)
498
-
499
- # ── Content pages ──
500
- for subj, chapters in grouped.items():
501
- pdf.add_page()
502
-
503
- # Subject section header
504
- pdf.ln(2)
505
- pdf.set_font('Helvetica', 'B', 14)
506
- pdf.set_text_color(*C_SECTION_RED)
507
- pdf._section_pill(subj)
508
-
509
- pdf.set_draw_color(*C_SECTION_RED)
510
- pdf.set_line_width(0.5)
511
- pdf.line(pdf.l_margin, pdf.get_y(), 192, pdf.get_y())
512
- pdf.ln(5)
513
-
514
- for chap, texts in chapters.items():
515
- # Chapter card
516
- pdf._chapter_card(chap)
517
-
518
- # Body content
519
- for raw_text in texts:
520
- cleaned = _clean(raw_text)
521
- if not cleaned:
522
- continue
523
- pdf._body_text(cleaned)
524
- pdf.ln(3)
525
-
526
- # Thin separator between chapters
527
- pdf.set_draw_color(*C_LIGHT_GREY)
528
- pdf.set_line_width(0.2)
529
- pdf.line(pdf.l_margin, pdf.get_y(), 192, pdf.get_y())
530
- pdf.ln(6)
531
-
532
- # ── Back / CTA page ──
533
- _draw_back_page(pdf)
534
-
535
- # ── Save ──
536
- output_dir = "data/digests"
537
- os.makedirs(output_dir, exist_ok=True)
538
-
539
- timestamp = datetime.now().strftime("%Y%m%d_%H%M")
540
- safe_ch = re.sub(r'[^\w]', '_', channel_name)
541
- safe_ct = re.sub(r'[^\w]', '_', content_type_label)
542
- filename = f"CrazyLearners_{safe_ch}_{safe_ct}_{timestamp}.pdf"
543
- file_path = os.path.join(os.getcwd(), output_dir, filename)
544
-
545
- pdf.output(file_path)
546
- logger.info(f"[OK] Branded PDF generated: {file_path} ({len(archive_items)} items)")
547
- return file_path
548
-
549
- except Exception as e:
550
- logger.error(f"[ERR] PDF generation failed: {e}", exc_info=True)
551
- return None
 
1
+ """
2
+ pdf_generator.py β€” Branded Weekly Digest PDF Generator
3
+ CrazyLearners | t.me/xcrazylearners
4
+
5
+ Layout (LaTeX-inspired with fpdf2):
6
+ β€’ Cover page β€” title, channel name, date, branding banner
7
+ β€’ TOC page β€” list of subjects + chapters
8
+ β€’ Content β€” Subject divider β†’ Chapter card β†’ body text (justified)
9
+ β€’ Every page β€” header with logo-text + footer with page no. + channel link
10
+ β€’ Last page β€” CrazyLearners branding / call-to-action
11
+
12
+ Fonts used (built-in fpdf2, no external download needed):
13
+ Helvetica β€” sans-serif (headings, UI chrome)
14
+ Courier β€” monospace (formula blocks)
15
+ """
16
+
17
+ import os
18
+ import re
19
+ import logging
20
+ from datetime import datetime
21
+ from fpdf import FPDF
22
+
23
+ logger = logging.getLogger(__name__)
24
+
25
+ # ─── Brand constants ────────────────────────────────────────────────────────────
26
+ BRAND_NAME = "CrazyLearners"
27
+ BRAND_HANDLE = "@xcrazylearners"
28
+ BRAND_LINK = "t.me/xcrazylearners"
29
+ BRAND_TAGLINE = "Learn Smarter. Score Higher."
30
+
31
+ # Colour palette (R, G, B)
32
+ C_BRAND_DARK = (15, 23, 42) # near-black navy β€” cover bg simulation (border)
33
+ C_BRAND_PURPLE = (79, 70, 229) # indigo-600 β€” primary accent
34
+ C_BRAND_TEAL = (20, 184, 166) # teal-500 β€” secondary accent
35
+ C_SECTION_RED = (220, 38, 38) # red-600 β€” subject headings
36
+ C_CHAPTER_BLU = (37, 99, 235) # blue-600 β€” chapter headings
37
+ C_BODY = (30, 30, 30) # near-black β€” body text
38
+ C_LIGHT_GREY = (200, 200, 200) # divider lines
39
+ C_WHITE = (255, 255, 255)
40
+ C_MID_GREY = (120, 120, 120) # captions / footnotes
41
+ C_GOLD = (217, 119, 6) # amber-600 β€” highlight boxes
42
+
43
+
44
+ # ─── Text helpers ────────────────────────────────────────────────────────────────
45
+
46
+ def _strip_markdown(text: str) -> str:
47
+ """Remove Markdown markers but preserve structure."""
48
+ if not text:
49
+ return ""
50
+ # Bold / Italic markers
51
+ text = re.sub(r'\*{1,3}(.*?)\*{1,3}', r'\1', text, flags=re.DOTALL)
52
+ text = re.sub(r'_{1,2}(.*?)_{1,2}', r'\1', text, flags=re.DOTALL)
53
+ # Inline code β†’ keep content, drop backticks
54
+ text = re.sub(r'`([^`]*)`', r'\1', text)
55
+ # Fenced code blocks β€” keep content
56
+ text = re.sub(r'```(?:\w+)?\n(.*?)```', r'\1', text, flags=re.DOTALL)
57
+ # Decorative separator lines (━━━ etc.)
58
+ text = re.sub(r'[━─=]{3,}', '---', text)
59
+ # Hashtags
60
+ text = re.sub(r'#\w+', '', text)
61
+ # Footer / brand lines already embedded in posts (we'll add our own)
62
+ text = re.sub(r'(CrazyLearners|xcrazylearners|t\.me/)', '', text, flags=re.I)
63
+ return text.strip()
64
+
65
+
66
+ def _safe_latin1(text: str) -> str:
67
+ """
68
+ fpdf2's built-in fonts (Helvetica/Courier) only support Latin-1.
69
+ Map common Unicode symbols to ASCII equivalents; drop the rest.
70
+ """
71
+ replacements = {
72
+ '\u2192': '->', '\u2190': '<-', '\u2194': '<->',
73
+ '\u2260': '!=', '\u2248': '~=', '\u2265': '>=',
74
+ '\u2264': '<=', '\u00b1': '+/-', '\u00d7': 'x',
75
+ '\u00f7': '/', '\u03b1': 'alpha', '\u03b2': 'beta',
76
+ '\u03b3': 'gamma', '\u03b4': 'delta', '\u03c0': 'pi',
77
+ '\u03bb': 'lambda', '\u03bc': 'mu', '\u03c3': 'sigma',
78
+ '\u03c9': 'omega', '\u00b2': '^2', '\u00b3': '^3',
79
+ '\u221a': 'sqrt', '\u221e': 'inf', '\u2211': 'sum',
80
+ '\u222b': 'int', '\u2202': 'd', '\u0394': 'Delta',
81
+ '\u03a9': 'Omega', '\u2019': "'", '\u2018': "'",
82
+ '\u201c': '"', '\u201d': '"',
83
+ '\u2022': '-', '\u2023': '>', '\u25cf': '*',
84
+ '\u2713': '[OK]', '\u2714': '[OK]', '\u2718': '[X]',
85
+ # Emojis β€” strip completely (map to empty string or label)
86
+ '\U0001f4da': '[BOOK]', '\U0001f4dd': '[NOTE]',
87
+ '\U0001f4a1': '[TIP]', '\U0001f3af': '[TARGET]',
88
+ '\U0001f525': '[FIRE]', '\U0001f9e0': '[BRAIN]',
89
+ '\U00002705': '[OK]', '\U0000274c': '[X]',
90
+ '\U000026a0': '[WARN]',
91
+ }
92
+ for uni, asc in replacements.items():
93
+ text = text.replace(uni, asc)
94
+ # Drop any remaining non-latin1 characters
95
+ text = text.encode('latin-1', errors='ignore').decode('latin-1')
96
+ # Collapse excessive blank lines
97
+ text = re.sub(r'\n{3,}', '\n\n', text)
98
+ return text.strip()
99
+
100
+
101
+ def _clean(text: str) -> str:
102
+ """Full pipeline: strip markdown β†’ safe latin-1."""
103
+ return _safe_latin1(_strip_markdown(text))
104
+
105
+
106
+ # ─── PDF Class ───────────────────────────────────────────────────────────────────
107
+
108
+ class BrandedPDF(FPDF):
109
+ """
110
+ CrazyLearners branded PDF with LaTeX-inspired layout.
111
+ Each page has a top header bar and a bottom footer bar.
112
+ """
113
+
114
+ def __init__(self, channel_label: str, content_type_label: str):
115
+ super().__init__(orientation='P', unit='mm', format='A4')
116
+ self.channel_label = _safe_latin1(channel_label)
117
+ self.content_type_label = _safe_latin1(content_type_label)
118
+ self.set_margins(left=18, top=28, right=18)
119
+ self.set_auto_page_break(auto=True, margin=22)
120
+
121
+ # ── Header (auto-called on every new page except cover) ──────────────────
122
+ def header(self):
123
+ if self.page == 1:
124
+ return # cover page handles its own layout
125
+
126
+ # Top rule
127
+ self.set_draw_color(*C_BRAND_PURPLE)
128
+ self.set_line_width(0.8)
129
+ self.line(10, 10, 200, 10)
130
+
131
+ # Brand name (left)
132
+ self.set_xy(10, 12)
133
+ self.set_font('Helvetica', 'B', 9)
134
+ self.set_text_color(*C_BRAND_PURPLE)
135
+ self.cell(80, 6, BRAND_NAME.upper(), align='L')
136
+
137
+ # Channel label (right)
138
+ self.set_xy(110, 12)
139
+ self.set_font('Helvetica', '', 8)
140
+ self.set_text_color(*C_MID_GREY)
141
+ self.cell(80, 6, self.channel_label, align='R')
142
+
143
+ self.ln(4)
144
+
145
+ # ── Footer ───────────────────────────────────────────────────────────────
146
+ def footer(self):
147
+ if self.page == 1:
148
+ return
149
+
150
+ self.set_y(-14)
151
+ self.set_draw_color(*C_LIGHT_GREY)
152
+ self.set_line_width(0.3)
153
+ self.line(10, self.get_y(), 200, self.get_y())
154
+ self.ln(1)
155
+
156
+ self.set_font('Helvetica', 'I', 7.5)
157
+ self.set_text_color(*C_MID_GREY)
158
+
159
+ # Left: page number
160
+ self.set_x(10)
161
+ self.cell(60, 5, f'Page {self.page_no()}', align='L')
162
+
163
+ # Centre: content type
164
+ self.set_x(70)
165
+ self.cell(60, 5, self.content_type_label, align='C')
166
+
167
+ # Right: channel link
168
+ self.set_x(130)
169
+ self.cell(60, 5, BRAND_LINK, align='R')
170
+
171
+ # ── Helpers ───────────────────────────────────────────────────────────────
172
+
173
+ def _hline(self, color=C_LIGHT_GREY, width=0.3, lm=18, rm=192):
174
+ self.set_draw_color(*color)
175
+ self.set_line_width(width)
176
+ self.line(lm, self.get_y(), rm, self.get_y())
177
+
178
+ def _filled_rect(self, x, y, w, h, fill_color, radius=2.0):
179
+ """Draw a filled rounded rectangle (section card background)."""
180
+ self.set_fill_color(*fill_color)
181
+ self.set_draw_color(*fill_color)
182
+ self.rounded_rect(x, y, w, h, radius, style='F')
183
+
184
+ def _section_pill(self, label: str):
185
+ """Draw a coloured pill/badge for the subject label."""
186
+ pill_w = 50
187
+ pill_h = 8
188
+ pill_x = self.l_margin
189
+ pill_y = self.get_y()
190
+ self._filled_rect(pill_x, pill_y, pill_w, pill_h,
191
+ fill_color=C_BRAND_PURPLE)
192
+ self.set_xy(pill_x, pill_y)
193
+ self.set_font('Helvetica', 'B', 9)
194
+ self.set_text_color(*C_WHITE)
195
+ self.cell(pill_w, pill_h, label.upper(), align='C')
196
+ self.ln(pill_h + 3)
197
+ self.set_text_color(*C_BODY)
198
+
199
+ def _chapter_card(self, chapter: str):
200
+ """Light teal card behind chapter heading."""
201
+ card_x = self.l_margin
202
+ card_y = self.get_y()
203
+ card_w = self.epw # effective page width
204
+ card_h = 9
205
+ # Light teal fill
206
+ self.set_fill_color(230, 255, 252)
207
+ self.set_draw_color(*C_BRAND_TEAL)
208
+ self.set_line_width(0.4)
209
+ self.rounded_rect(card_x, card_y, card_w, card_h, 2, style='FD')
210
+
211
+ self.set_xy(card_x + 3, card_y + 1.5)
212
+ self.set_font('Helvetica', 'B', 10)
213
+ self.set_text_color(*C_CHAPTER_BLU)
214
+ self.cell(card_w - 6, 6, f' Chapter: {_safe_latin1(chapter)}')
215
+ self.ln(card_h + 2)
216
+ self.set_text_color(*C_BODY)
217
+
218
+ def _body_text(self, text: str):
219
+ """
220
+ Render body text with LaTeX-like paragraph handling.
221
+ Lines starting with '-', '*', or a number followed by '.' are bullet points.
222
+ Lines with ALL CAPS or ending with ':' are treated as sub-headings.
223
+ """
224
+ paragraphs = text.split('\n')
225
+ self.set_font('Helvetica', '', 9.5)
226
+ self.set_text_color(*C_BODY)
227
+
228
+ for para in paragraphs:
229
+ para = para.strip()
230
+ if not para:
231
+ self.ln(2.5)
232
+ continue
233
+
234
+ # Horizontal rule placeholder
235
+ if para.startswith('---'):
236
+ self._hline(C_LIGHT_GREY, 0.2)
237
+ self.ln(2)
238
+ continue
239
+
240
+ # Sub-heading detection: ends with ':' or ALL-CAPS short line
241
+ is_subhead = (
242
+ (para.endswith(':') and len(para) < 80) or
243
+ (para.isupper() and len(para) < 60)
244
+ )
245
+ if is_subhead:
246
+ self.ln(1)
247
+ self.set_font('Helvetica', 'B', 9.5)
248
+ self.set_text_color(*C_BRAND_PURPLE)
249
+ self.multi_cell(0, 5.5, para, align='L')
250
+ self.set_font('Helvetica', '', 9.5)
251
+ self.set_text_color(*C_BODY)
252
+ self.ln(0.5)
253
+ continue
254
+
255
+ # Bullet points
256
+ if re.match(r'^[-*\u2022]\s+', para):
257
+ bullet_text = re.sub(r'^[-*\u2022]\s+', '', para)
258
+ self.set_x(self.l_margin + 5)
259
+ self.set_font('Helvetica', '', 9.5)
260
+ self.cell(4, 5.5, '-')
261
+ self.multi_cell(self.epw - 9, 5.5, _safe_latin1(bullet_text), align='L')
262
+ continue
263
+
264
+ # Numbered list
265
+ if re.match(r'^\d+[.)]\s+', para):
266
+ self.set_x(self.l_margin + 2)
267
+ self.multi_cell(0, 5.5, _safe_latin1(para), align='L')
268
+ continue
269
+
270
+ # Normal paragraph β€” justified
271
+ self.multi_cell(0, 5.5, _safe_latin1(para), align='J')
272
+ self.ln(1)
273
+
274
+
275
+ # ─── Cover Page ─────────────────────────────────────────────────────────────────
276
+
277
+ def _draw_cover(pdf: BrandedPDF, channel_name: str,
278
+ content_type_label: str, week_range: str):
279
+ """
280
+ Draw a premium-looking cover page:
281
+ top accent bar | title block | meta block | branding block
282
+ """
283
+ A4_W, A4_H = 210, 297
284
+
285
+ # ── Top accent bar (full width) ──
286
+ pdf.set_fill_color(*C_BRAND_PURPLE)
287
+ pdf.rect(0, 0, A4_W, 18, style='F')
288
+
289
+ # Brand name in the bar
290
+ pdf.set_xy(0, 4)
291
+ pdf.set_font('Helvetica', 'B', 11)
292
+ pdf.set_text_color(*C_WHITE)
293
+ pdf.cell(A4_W, 10, BRAND_NAME.upper() + ' | ' + BRAND_HANDLE, align='C')
294
+
295
+ # ── Second teal stripe ──
296
+ pdf.set_fill_color(*C_BRAND_TEAL)
297
+ pdf.rect(0, 18, A4_W, 4, style='F')
298
+
299
+ # ── Central title block ──
300
+ pdf.set_xy(20, 65)
301
+ pdf.set_font('Helvetica', 'B', 28)
302
+ pdf.set_text_color(*C_BRAND_DARK)
303
+ pdf.multi_cell(170, 14, _safe_latin1(content_type_label).upper(), align='C')
304
+
305
+ # Underline the title
306
+ title_y = pdf.get_y() + 2
307
+ pdf.set_draw_color(*C_BRAND_PURPLE)
308
+ pdf.set_line_width(1.2)
309
+ pdf.line(45, title_y, 165, title_y)
310
+ pdf.ln(10)
311
+
312
+ # Channel name
313
+ pdf.set_font('Helvetica', 'B', 16)
314
+ pdf.set_text_color(*C_BRAND_PURPLE)
315
+ pdf.cell(0, 12, _safe_latin1(channel_name), align='C', new_x='LMARGIN', new_y='NEXT')
316
+
317
+ # Week range
318
+ pdf.set_font('Helvetica', '', 12)
319
+ pdf.set_text_color(*C_MID_GREY)
320
+ pdf.cell(0, 8, week_range, align='C', new_x='LMARGIN', new_y='NEXT')
321
+ pdf.ln(6)
322
+
323
+ # Tagline
324
+ pdf.set_font('Helvetica', 'I', 12)
325
+ pdf.set_text_color(*C_GOLD)
326
+ pdf.cell(0, 8, BRAND_TAGLINE, align='C', new_x='LMARGIN', new_y='NEXT')
327
+ pdf.ln(40)
328
+
329
+ # ── Bottom branding box ──
330
+ box_y = A4_H - 70
331
+ pdf.set_fill_color(245, 245, 255)
332
+ pdf.set_draw_color(*C_BRAND_PURPLE)
333
+ pdf.set_line_width(0.5)
334
+ pdf.rounded_rect(20, box_y, A4_W - 40, 45, 4, style='FD')
335
+
336
+ pdf.set_xy(20, box_y + 6)
337
+ pdf.set_font('Helvetica', 'B', 11)
338
+ pdf.set_text_color(*C_BRAND_PURPLE)
339
+ pdf.cell(A4_W - 40, 8, 'JOIN OUR COMMUNITY', align='C', new_x='LMARGIN', new_y='NEXT')
340
+
341
+ pdf.set_x(20)
342
+ pdf.set_font('Helvetica', '', 10)
343
+ pdf.set_text_color(*C_BODY)
344
+ pdf.cell(A4_W - 40, 7,
345
+ 'Daily Notes | Formula Sheets | PYQ Sessions | MCQ Polls',
346
+ align='C', new_x='LMARGIN', new_y='NEXT')
347
+
348
+ pdf.set_x(20)
349
+ pdf.set_font('Helvetica', 'B', 12)
350
+ pdf.set_text_color(*C_BRAND_TEAL)
351
+ pdf.cell(A4_W - 40, 9, BRAND_LINK, align='C', new_x='LMARGIN', new_y='NEXT')
352
+
353
+ pdf.set_x(20)
354
+ pdf.set_font('Helvetica', '', 9)
355
+ pdf.set_text_color(*C_MID_GREY)
356
+ pdf.cell(A4_W - 40, 7,
357
+ f'Generated: {datetime.now().strftime("%d %b %Y, %I:%M %p IST")}',
358
+ align='C')
359
+
360
+ # ── Bottom stripe ──
361
+ pdf.set_fill_color(*C_BRAND_TEAL)
362
+ pdf.rect(0, A4_H - 12, A4_W, 12, style='F')
363
+ pdf.set_xy(0, A4_H - 10)
364
+ pdf.set_font('Helvetica', 'I', 8)
365
+ pdf.set_text_color(*C_WHITE)
366
+ pdf.cell(A4_W, 8, 'Free for personal use. Share freely!', align='C')
367
+
368
+
369
+ # ─── Table of Contents ───────────────────────────────────────────────────────────
370
+
371
+ def _draw_toc(pdf: BrandedPDF, grouped: dict):
372
+ pdf.add_page()
373
+ pdf.set_font('Helvetica', 'B', 16)
374
+ pdf.set_text_color(*C_BRAND_PURPLE)
375
+ pdf.cell(0, 12, 'TABLE OF CONTENTS', new_x='LMARGIN', new_y='NEXT', align='C')
376
+ pdf.set_draw_color(*C_BRAND_PURPLE)
377
+ pdf.set_line_width(0.6)
378
+ pdf.line(18, pdf.get_y(), 192, pdf.get_y())
379
+ pdf.ln(6)
380
+
381
+ entry_num = 1
382
+ for subj, chapters in grouped.items():
383
+ pdf.set_font('Helvetica', 'B', 11)
384
+ pdf.set_text_color(*C_SECTION_RED)
385
+ pdf.cell(0, 8, f'{subj}', new_x='LMARGIN', new_y='NEXT')
386
+
387
+ pdf.set_font('Helvetica', '', 10)
388
+ pdf.set_text_color(*C_BODY)
389
+ for chap in chapters.keys():
390
+ safe_chap = _safe_latin1(chap)
391
+ # Dot leader
392
+ pdf.set_x(pdf.l_margin + 6)
393
+ pdf.cell(4, 6.5, str(entry_num) + '.')
394
+ pdf.cell(130, 6.5, safe_chap[:65])
395
+ entry_num += 1
396
+ pdf.ln(6.5)
397
+ pdf.ln(2)
398
+
399
+
400
+ # ─── Back / CTA page ─────────────────────────────────────────────────────────────
401
+
402
+ def _draw_back_page(pdf: BrandedPDF):
403
+ pdf.add_page()
404
+ A4_W = 210
405
+
406
+ pdf.ln(30)
407
+ pdf.set_font('Helvetica', 'B', 22)
408
+ pdf.set_text_color(*C_BRAND_PURPLE)
409
+ pdf.cell(0, 14, 'Keep Learning, Keep Growing!', align='C', new_x='LMARGIN', new_y='NEXT')
410
+
411
+ pdf.set_font('Helvetica', 'I', 13)
412
+ pdf.set_text_color(*C_MID_GREY)
413
+ pdf.cell(0, 9, BRAND_TAGLINE, align='C', new_x='LMARGIN', new_y='NEXT')
414
+ pdf.ln(20)
415
+
416
+ # Info box
417
+ box_y = pdf.get_y()
418
+ pdf.set_fill_color(240, 240, 255)
419
+ pdf.set_draw_color(*C_BRAND_PURPLE)
420
+ pdf.set_line_width(0.5)
421
+ pdf.rounded_rect(25, box_y, A4_W - 50, 80, 5, style='FD')
422
+
423
+ pdf.set_xy(25, box_y + 10)
424
+ pdf.set_font('Helvetica', 'B', 13)
425
+ pdf.set_text_color(*C_BRAND_PURPLE)
426
+ pdf.cell(A4_W - 50, 10, 'What we offer daily:', align='C', new_x='LMARGIN', new_y='NEXT')
427
+
428
+ items = [
429
+ '[NOTE] Short Notes & Formula Sheets',
430
+ '[TARGET] PYQ Questions with Solutions',
431
+ '[BRAIN] Memory Tricks & Mnemonics',
432
+ '[FIRE] MCQ Poll Sessions (10 Questions)',
433
+ '[TIP] Concept Recaps & Mock Questions',
434
+ ]
435
+ pdf.set_font('Helvetica', '', 11)
436
+ pdf.set_text_color(*C_BODY)
437
+ for item in items:
438
+ pdf.set_x(35)
439
+ pdf.cell(A4_W - 70, 9, item, new_x='LMARGIN', new_y='NEXT')
440
+
441
+ pdf.ln(25)
442
+ pdf.set_font('Helvetica', 'B', 16)
443
+ pdf.set_text_color(*C_BRAND_TEAL)
444
+ pdf.cell(0, 12, BRAND_LINK, align='C', new_x='LMARGIN', new_y='NEXT')
445
+
446
+ pdf.set_font('Helvetica', '', 10)
447
+ pdf.set_text_color(*C_MID_GREY)
448
+ pdf.cell(0, 8, 'Tap the link in Telegram to join!', align='C')
449
+
450
+ # Bottom bar
451
+ pdf.set_fill_color(*C_BRAND_PURPLE)
452
+ pdf.rect(0, 285, A4_W, 12, style='F')
453
+ pdf.set_xy(0, 287)
454
+ pdf.set_font('Helvetica', 'I', 8)
455
+ pdf.set_text_color(*C_WHITE)
456
+ pdf.cell(A4_W, 8, f'{BRAND_NAME} | {BRAND_LINK} | Free to share!', align='C')
457
+
458
+
459
+ # ─── Public API ──────────────────────────────────────────────────────────────────
460
+
461
+ def create_digest_pdf(channel_name: str, content_type_label: str,
462
+ archive_items: list) -> str:
463
+ """
464
+ Creates a branded, LaTeX-inspired chapter-wise PDF from archived posts.
465
+
466
+ Args:
467
+ channel_name: Human-readable channel label (e.g. "JEE Advanced Daily")
468
+ content_type_label: e.g. "Short Notes" or "Formula Sheet"
469
+ archive_items: List of dicts: [{subject, chapter, text, date}, ...]
470
+
471
+ Returns:
472
+ Absolute path to the generated PDF, or None on failure.
473
+ """
474
+ if not archive_items:
475
+ logger.warning("create_digest_pdf called with empty archive_items")
476
+ return None
477
+
478
+ try:
479
+ pdf = BrandedPDF(channel_name, content_type_label)
480
+
481
+ # ── Cover page (page 1) ──
482
+ pdf.add_page()
483
+ now = datetime.now()
484
+ week_start = now.strftime("%d %b") # approximate β€” Sunday digest
485
+ week_range = f'Week of {week_start} {now.year}'
486
+ _draw_cover(pdf, channel_name, f'Weekly {content_type_label}', week_range)
487
+
488
+ # ── Group archive by Subject β†’ Chapter ──
489
+ grouped: dict = {}
490
+ for item in archive_items:
491
+ subj = str(item.get('subject', 'General')).title()
492
+ chap = str(item.get('chapter', 'General'))
493
+ text = str(item.get('text', ''))
494
+ grouped.setdefault(subj, {}).setdefault(chap, []).append(text)
495
+
496
+ # ── Table of Contents (page 2) ──
497
+ _draw_toc(pdf, grouped)
498
+
499
+ # ── Content pages ──
500
+ for subj, chapters in grouped.items():
501
+ pdf.add_page()
502
+
503
+ # Subject section header
504
+ pdf.ln(2)
505
+ pdf.set_font('Helvetica', 'B', 14)
506
+ pdf.set_text_color(*C_SECTION_RED)
507
+ pdf._section_pill(subj)
508
+
509
+ pdf.set_draw_color(*C_SECTION_RED)
510
+ pdf.set_line_width(0.5)
511
+ pdf.line(pdf.l_margin, pdf.get_y(), 192, pdf.get_y())
512
+ pdf.ln(5)
513
+
514
+ for chap, texts in chapters.items():
515
+ # Chapter card
516
+ pdf._chapter_card(chap)
517
+
518
+ # Body content
519
+ for raw_text in texts:
520
+ cleaned = _clean(raw_text)
521
+ if not cleaned:
522
+ continue
523
+ pdf._body_text(cleaned)
524
+ pdf.ln(3)
525
+
526
+ # Thin separator between chapters
527
+ pdf.set_draw_color(*C_LIGHT_GREY)
528
+ pdf.set_line_width(0.2)
529
+ pdf.line(pdf.l_margin, pdf.get_y(), 192, pdf.get_y())
530
+ pdf.ln(6)
531
+
532
+ # ── Back / CTA page ──
533
+ _draw_back_page(pdf)
534
+
535
+ # ── Save ──
536
+ output_dir = "data/digests"
537
+ os.makedirs(output_dir, exist_ok=True)
538
+
539
+ timestamp = datetime.now().strftime("%Y%m%d_%H%M")
540
+ safe_ch = re.sub(r'[^\w]', '_', channel_name)
541
+ safe_ct = re.sub(r'[^\w]', '_', content_type_label)
542
+ filename = f"CrazyLearners_{safe_ch}_{safe_ct}_{timestamp}.pdf"
543
+ file_path = os.path.join(os.getcwd(), output_dir, filename)
544
+
545
+ pdf.output(file_path)
546
+ logger.info(f"[OK] Branded PDF generated: {file_path} ({len(archive_items)} items)")
547
+ return file_path
548
+
549
+ except Exception as e:
550
+ logger.error(f"[ERR] PDF generation failed: {e}", exc_info=True)
551
+ return None
content/remote_storage.py CHANGED
@@ -1,72 +1,72 @@
1
- import json
2
- import logging
3
- import requests
4
- logger = logging.getLogger(__name__)
5
-
6
- def pull_from_gist(filename: str) -> dict:
7
- """Pull a specific JSON file from the GitHub Gist."""
8
- from config import GIST_ID, GIST_TOKEN
9
- if not GIST_ID or not GIST_TOKEN:
10
- return None
11
-
12
- try:
13
- url = f"https://api.github.com/gists/{GIST_ID}"
14
- headers = {"Authorization": f"token {GIST_TOKEN}"}
15
- resp = requests.get(url, headers=headers, timeout=10)
16
-
17
- if resp.status_code == 200:
18
- gist_data = resp.json()
19
- files = gist_data.get("files", {})
20
- if filename in files:
21
- content = files[filename].get("content", "{}")
22
- logger.info(f"Successfully pulled {filename} from Gist")
23
- return json.loads(content)
24
- elif resp.status_code == 401:
25
- logger.error(f"Gist Pull Failed ({filename}): [401 Unauthorized] Check your GIST_TOKEN.")
26
- elif resp.status_code != 404:
27
- logger.error(f"Failed to pull {filename} from Gist (Status {resp.status_code})")
28
- except Exception as e:
29
- logger.error(f"Error pulling {filename} from Gist: {e}")
30
-
31
- return None
32
-
33
-
34
- def push_to_gist(filename: str, data_dict: dict):
35
- """Push a dictionary to a specific file in the GitHub Gist."""
36
- from config import GIST_ID, GIST_TOKEN
37
- if not GIST_ID or not GIST_TOKEN:
38
- return
39
-
40
- try:
41
- url = f"https://api.github.com/gists/{GIST_ID}"
42
- headers = {"Authorization": f"token {GIST_TOKEN}"}
43
-
44
- content = json.dumps(data_dict, indent=2)
45
- payload = {
46
- "files": {
47
- filename: {
48
- "content": content
49
- }
50
- }
51
- }
52
-
53
- resp = requests.patch(url, headers=headers, json=payload, timeout=10)
54
-
55
- if resp.status_code == 200:
56
- logger.info(f"Successfully pushed {filename} to Gist")
57
- elif resp.status_code == 401:
58
- logger.error(f"Gist Push Failed ({filename}): [401 Unauthorized] Check your GIST_TOKEN.")
59
- else:
60
- logger.error(f"Failed to push {filename} to Gist (Status {resp.status_code})")
61
- except Exception as e:
62
- logger.error(f"Error pushing {filename} to Gist: {e}")
63
-
64
-
65
- # ── Legacy Wrappers (to avoid breaking other files) ───────────────────────────
66
- def pull_history_from_gist() -> dict:
67
- from config import HISTORY_FILE_NAME
68
- return pull_from_gist(HISTORY_FILE_NAME)
69
-
70
- def push_history_to_gist(history_dict: dict):
71
- from config import HISTORY_FILE_NAME
72
- push_to_gist(HISTORY_FILE_NAME, history_dict)
 
1
+ import json
2
+ import logging
3
+ import requests
4
+ logger = logging.getLogger(__name__)
5
+
6
+ def pull_from_gist(filename: str) -> dict:
7
+ """Pull a specific JSON file from the GitHub Gist."""
8
+ from config import GIST_ID, GIST_TOKEN
9
+ if not GIST_ID or not GIST_TOKEN:
10
+ return None
11
+
12
+ try:
13
+ url = f"https://api.github.com/gists/{GIST_ID}"
14
+ headers = {"Authorization": f"token {GIST_TOKEN}"}
15
+ resp = requests.get(url, headers=headers, timeout=10)
16
+
17
+ if resp.status_code == 200:
18
+ gist_data = resp.json()
19
+ files = gist_data.get("files", {})
20
+ if filename in files:
21
+ content = files[filename].get("content", "{}")
22
+ logger.info(f"Successfully pulled {filename} from Gist")
23
+ return json.loads(content)
24
+ elif resp.status_code == 401:
25
+ logger.error(f"Gist Pull Failed ({filename}): [401 Unauthorized] Check your GIST_TOKEN.")
26
+ elif resp.status_code != 404:
27
+ logger.error(f"Failed to pull {filename} from Gist (Status {resp.status_code})")
28
+ except Exception as e:
29
+ logger.error(f"Error pulling {filename} from Gist: {e}")
30
+
31
+ return None
32
+
33
+
34
+ def push_to_gist(filename: str, data_dict: dict):
35
+ """Push a dictionary to a specific file in the GitHub Gist."""
36
+ from config import GIST_ID, GIST_TOKEN
37
+ if not GIST_ID or not GIST_TOKEN:
38
+ return
39
+
40
+ try:
41
+ url = f"https://api.github.com/gists/{GIST_ID}"
42
+ headers = {"Authorization": f"token {GIST_TOKEN}"}
43
+
44
+ content = json.dumps(data_dict, indent=2)
45
+ payload = {
46
+ "files": {
47
+ filename: {
48
+ "content": content
49
+ }
50
+ }
51
+ }
52
+
53
+ resp = requests.patch(url, headers=headers, json=payload, timeout=10)
54
+
55
+ if resp.status_code == 200:
56
+ logger.info(f"Successfully pushed {filename} to Gist")
57
+ elif resp.status_code == 401:
58
+ logger.error(f"Gist Push Failed ({filename}): [401 Unauthorized] Check your GIST_TOKEN.")
59
+ else:
60
+ logger.error(f"Failed to push {filename} to Gist (Status {resp.status_code})")
61
+ except Exception as e:
62
+ logger.error(f"Error pushing {filename} to Gist: {e}")
63
+
64
+
65
+ # ── Legacy Wrappers (to avoid breaking other files) ───────────────────────────
66
+ def pull_history_from_gist() -> dict:
67
+ from config import HISTORY_FILE_NAME
68
+ return pull_from_gist(HISTORY_FILE_NAME)
69
+
70
+ def push_history_to_gist(history_dict: dict):
71
+ from config import HISTORY_FILE_NAME
72
+ push_to_gist(HISTORY_FILE_NAME, history_dict)
content/syllabus_manager.py CHANGED
@@ -1,109 +1,109 @@
1
- import json
2
- import os
3
- import logging
4
- from typing import List, Dict
5
-
6
- logger = logging.getLogger(__name__)
7
-
8
- SYLLABUS_FILE = "data/syllabus.json"
9
-
10
- class SyllabusManager:
11
- def __init__(self):
12
- self.syllabus = {}
13
- self.load_syllabus()
14
-
15
- # Map channel focus strings to JSON keys
16
- self.focus_map = {
17
- "JEE Main": "JEE_MAINS_2026",
18
- "JEE Advanced": "JEE_ADVANCED_2026",
19
- "NEET": "NEET_UG_2026"
20
- }
21
-
22
- def load_syllabus(self):
23
- """Loads the comprehensive syllabus JSON from data/syllabus.json."""
24
- if not os.path.exists(SYLLABUS_FILE):
25
- logger.error(f"Syllabus file NOT FOUND: {SYLLABUS_FILE}")
26
- return
27
-
28
- try:
29
- with open(SYLLABUS_FILE, "r") as f:
30
- self.syllabus = json.load(f)
31
- logger.info(f"[OK] Syllabus loaded successfully from {SYLLABUS_FILE}")
32
- except Exception as e:
33
- logger.error(f"Error loading syllabus: {e}")
34
-
35
- def save_syllabus(self, syllabus_data: dict) -> bool:
36
- """Saves a new syllabus dictionary to the data/syllabus.json file."""
37
- try:
38
- os.makedirs(os.path.dirname(SYLLABUS_FILE), exist_ok=True)
39
- with open(SYLLABUS_FILE, "w") as f:
40
- json.dump(syllabus_data, f, indent=2)
41
- self.syllabus = syllabus_data
42
- logger.info(f"[OK] Syllabus saved successfully to {SYLLABUS_FILE}")
43
- return True
44
- except Exception as e:
45
- logger.error(f"Error saving syllabus: {e}")
46
- return False
47
-
48
- def get_chapters(self, exam_focus_list: List[str], subject: str) -> List[str]:
49
- """
50
- Retrieves a flattened list of all chapters/topics for a given subject
51
- across multiple exam focuses (e.g., both JEE Main and Advanced).
52
- """
53
- all_topics = set()
54
- # Normalize subject names to match JSON keys
55
- subject_map = {
56
- "maths": "Mathematics",
57
- "biology": "Biology",
58
- "physics": "Physics",
59
- "chemistry": "Chemistry"
60
- }
61
- subject = subject_map.get(subject.lower(), subject.title())
62
-
63
- for focus in exam_focus_list:
64
- json_key = self.focus_map.get(focus)
65
- if not json_key or json_key not in self.syllabus:
66
- continue
67
-
68
- exam_data = self.syllabus[json_key]
69
- # Navigate to the subject block
70
- subjects_block = exam_data.get("Subjects", {})
71
-
72
- # Subject names in JSON are properly capitalized (Physics, Chemistry, etc.)
73
- subject_key = next((k for k in subjects_block.keys() if k.lower() == subject.lower()), None)
74
- if not subject_key:
75
- continue
76
-
77
- subj_data = subjects_block[subject_key]
78
-
79
- # Extract topics recursively from any nested structure
80
- all_topics.update(self._extract_topics(subj_data))
81
-
82
- flattened = sorted(list(all_topics))
83
- if not flattened:
84
- logger.warning(f"No topics found for focus {exam_focus_list} and subject {subject}")
85
- return ["General"]
86
-
87
- return flattened
88
-
89
- def _extract_topics(self, data) -> List[str]:
90
- """Recursively extracts string topics from nested dictionaries and lists."""
91
- topics = []
92
- if isinstance(data, list):
93
- topics.extend([str(item) for item in data])
94
- elif isinstance(data, dict):
95
- for val in data.values():
96
- topics.extend(self._extract_topics(val))
97
- return topics
98
-
99
- def get_all_subjects(self, exam_focus: str) -> List[str]:
100
- """Returns the list of subjects available for a specific exam (e.g., biology for NEET)."""
101
- json_key = self.focus_map.get(exam_focus)
102
- if not json_key or json_key not in self.syllabus:
103
- return ["physics", "chemistry", "maths"]
104
-
105
- subjects = self.syllabus[json_key].get("Subjects", {}).keys()
106
- return [s.lower() for s in subjects]
107
-
108
- # Singleton instance for the bot
109
- syllabus_manager = SyllabusManager()
 
1
+ import json
2
+ import os
3
+ import logging
4
+ from typing import List, Dict
5
+
6
+ logger = logging.getLogger(__name__)
7
+
8
+ SYLLABUS_FILE = "data/syllabus.json"
9
+
10
+ class SyllabusManager:
11
+ def __init__(self):
12
+ self.syllabus = {}
13
+ self.load_syllabus()
14
+
15
+ # Map channel focus strings to JSON keys
16
+ self.focus_map = {
17
+ "JEE Main": "JEE_MAINS_2026",
18
+ "JEE Advanced": "JEE_ADVANCED_2026",
19
+ "NEET": "NEET_UG_2026"
20
+ }
21
+
22
+ def load_syllabus(self):
23
+ """Loads the comprehensive syllabus JSON from data/syllabus.json."""
24
+ if not os.path.exists(SYLLABUS_FILE):
25
+ logger.error(f"Syllabus file NOT FOUND: {SYLLABUS_FILE}")
26
+ return
27
+
28
+ try:
29
+ with open(SYLLABUS_FILE, "r") as f:
30
+ self.syllabus = json.load(f)
31
+ logger.info(f"[OK] Syllabus loaded successfully from {SYLLABUS_FILE}")
32
+ except Exception as e:
33
+ logger.error(f"Error loading syllabus: {e}")
34
+
35
+ def save_syllabus(self, syllabus_data: dict) -> bool:
36
+ """Saves a new syllabus dictionary to the data/syllabus.json file."""
37
+ try:
38
+ os.makedirs(os.path.dirname(SYLLABUS_FILE), exist_ok=True)
39
+ with open(SYLLABUS_FILE, "w") as f:
40
+ json.dump(syllabus_data, f, indent=2)
41
+ self.syllabus = syllabus_data
42
+ logger.info(f"[OK] Syllabus saved successfully to {SYLLABUS_FILE}")
43
+ return True
44
+ except Exception as e:
45
+ logger.error(f"Error saving syllabus: {e}")
46
+ return False
47
+
48
+ def get_chapters(self, exam_focus_list: List[str], subject: str) -> List[str]:
49
+ """
50
+ Retrieves a flattened list of all chapters/topics for a given subject
51
+ across multiple exam focuses (e.g., both JEE Main and Advanced).
52
+ """
53
+ all_topics = set()
54
+ # Normalize subject names to match JSON keys
55
+ subject_map = {
56
+ "maths": "Mathematics",
57
+ "biology": "Biology",
58
+ "physics": "Physics",
59
+ "chemistry": "Chemistry"
60
+ }
61
+ subject = subject_map.get(subject.lower(), subject.title())
62
+
63
+ for focus in exam_focus_list:
64
+ json_key = self.focus_map.get(focus)
65
+ if not json_key or json_key not in self.syllabus:
66
+ continue
67
+
68
+ exam_data = self.syllabus[json_key]
69
+ # Navigate to the subject block
70
+ subjects_block = exam_data.get("Subjects", {})
71
+
72
+ # Subject names in JSON are properly capitalized (Physics, Chemistry, etc.)
73
+ subject_key = next((k for k in subjects_block.keys() if k.lower() == subject.lower()), None)
74
+ if not subject_key:
75
+ continue
76
+
77
+ subj_data = subjects_block[subject_key]
78
+
79
+ # Extract topics recursively from any nested structure
80
+ all_topics.update(self._extract_topics(subj_data))
81
+
82
+ flattened = sorted(list(all_topics))
83
+ if not flattened:
84
+ logger.warning(f"No topics found for focus {exam_focus_list} and subject {subject}")
85
+ return ["General"]
86
+
87
+ return flattened
88
+
89
+ def _extract_topics(self, data) -> List[str]:
90
+ """Recursively extracts string topics from nested dictionaries and lists."""
91
+ topics = []
92
+ if isinstance(data, list):
93
+ topics.extend([str(item) for item in data])
94
+ elif isinstance(data, dict):
95
+ for val in data.values():
96
+ topics.extend(self._extract_topics(val))
97
+ return topics
98
+
99
+ def get_all_subjects(self, exam_focus: str) -> List[str]:
100
+ """Returns the list of subjects available for a specific exam (e.g., biology for NEET)."""
101
+ json_key = self.focus_map.get(exam_focus)
102
+ if not json_key or json_key not in self.syllabus:
103
+ return ["physics", "chemistry", "maths"]
104
+
105
+ subjects = self.syllabus[json_key].get("Subjects", {}).keys()
106
+ return [s.lower() for s in subjects]
107
+
108
+ # Singleton instance for the bot
109
+ syllabus_manager = SyllabusManager()
content/template_manager.py CHANGED
@@ -1,113 +1,113 @@
1
- import json
2
- import os
3
- import logging
4
- from typing import Dict
5
-
6
- logger = logging.getLogger(__name__)
7
-
8
- PROMPTS_FILE = "data/prompts.json"
9
-
10
- DEFAULT_SYSTEM_PROMPT = """You are an expert JEE/NEET educator creating Telegram channel posts.
11
-
12
- STRICT FORMATTING RULES:
13
- 1. Use <b>text</b> for bold headers and section titles
14
- 2. Use <i>text</i> for italics (sparingly)
15
- 3. Write formulas in plain text using Unicode: Γ— Γ· Ξ” Ξ± Ξ² Ο€ √ β‰ˆ β‰  ≀ β‰₯
16
- Example: Kp = Kc Γ— (RT)^Ξ”n ← correct
17
- Never use: $Kp = Kc(RT)^{\\Delta n}$ or backticks for formulas
18
- 4. Use β€’ for bullet points
19
- 5. Do NOT use: ##headers, LaTeX, markdown tables, code blocks
20
- 6. Keep output under 3800 characters
21
- """
22
-
23
- DEFAULT_TEMPLATES = {
24
- "pyq_question": "Generate a realistic Previous Year Question (PYQ) style MCQ for {exam} {year} on the topic \"{chapter}\" from {subject}.",
25
- "formula_sheet": "Generate a concise 'Formula and Concept Cheat Sheet' for {exam} on the chapter \"{chapter}\" ({subject}).",
26
- "short_notes": "Create 'Rapid Revision Notes' for {exam} on \"{chapter}\" from {subject}.",
27
- "motivational": "Write a short, powerful motivational message for an exam aspirant studying {subject}. Topic: {chapter}",
28
- "concept_recap": "Explain one non-obvious, crucial concept from \"{chapter}\" ({subject}) that often appears in {exam}.",
29
- "mnemonic": "Create a catchy mnemonic or memory trick to remember a complex set of facts/formulas in \"{chapter}\" ({subject}).",
30
- "mock_question": "Generate a high-yield 'Mock Challenge' MCQ for {exam} on \"{chapter}\" ({subject}).",
31
- "mcq_session": """Generate exactly 10 high-quality multiple-choice questions (MCQs) for {exam} on the chapter "{chapter}" ({subject}).
32
-
33
- IMPORTANT: Return the response ONLY as a JSON array of objects. Do not include any conversational text.
34
-
35
- Format:
36
- [
37
- {{
38
- "question": "Full question text...",
39
- "options": ["Option A", "Option B", "Option C", "Option D"],
40
- "correct_index": 0,
41
- "explanation": "Why is this the correct answer?"
42
- }},
43
- ...
44
- ]
45
-
46
- Ensure questions vary in difficulty and cover the entire chapter.
47
- """
48
- }
49
-
50
- class TemplateManager:
51
- def __init__(self):
52
- self.data = {
53
- "system_prompt": DEFAULT_SYSTEM_PROMPT,
54
- "templates": DEFAULT_TEMPLATES.copy()
55
- }
56
- self.load_prompts()
57
-
58
- def load_prompts(self):
59
- """Load prompts from Gist (remote) or JSON file (local)."""
60
- # 1. Try to pull from Gist first
61
- from content.remote_storage import pull_from_gist
62
- remote_data = pull_from_gist(os.path.basename(PROMPTS_FILE))
63
- if remote_data:
64
- if "system_prompt" in remote_data:
65
- self.data["system_prompt"] = remote_data["system_prompt"]
66
- if "templates" in remote_data:
67
- self.data["templates"].update(remote_data["templates"])
68
- logger.info(f"[OK] Prompts loaded from Gist")
69
- # Save locally
70
- self._save_local()
71
- return
72
-
73
- # 2. Fallback to local file
74
- if not os.path.exists(PROMPTS_FILE):
75
- return
76
- try:
77
- with open(PROMPTS_FILE, "r") as f:
78
- loaded_data = json.load(f)
79
- if "system_prompt" in loaded_data:
80
- self.data["system_prompt"] = loaded_data["system_prompt"]
81
- if "templates" in loaded_data:
82
- self.data["templates"].update(loaded_data["templates"])
83
- logger.info(f"[OK] Prompts loaded from {PROMPTS_FILE}")
84
- except Exception as e:
85
- logger.error(f"Error loading prompts: {e}")
86
-
87
- def _save_local(self):
88
- """Internal helper to save prompts to local file."""
89
- try:
90
- os.makedirs(os.path.dirname(PROMPTS_FILE), exist_ok=True)
91
- with open(PROMPTS_FILE, "w") as f:
92
- json.dump(self.data, f, indent=2)
93
- except Exception as e:
94
- logger.error(f"[LOCAL PROMPT SAVE ERROR] {e}")
95
-
96
- def save_prompts(self, data: dict) -> bool:
97
- """Save prompts locally and to GitHub Gist."""
98
- self.data = data
99
- self._save_local()
100
-
101
- # Push to Gist
102
- from content.remote_storage import push_to_gist
103
- push_to_gist(os.path.basename(PROMPTS_FILE), data)
104
- return True
105
-
106
- def get_template(self, content_type: str) -> str:
107
- return self.data.get("templates", {}).get(content_type, DEFAULT_TEMPLATES.get(content_type, ""))
108
-
109
- @property
110
- def system_prompt(self) -> str:
111
- return self.data.get("system_prompt", "")
112
-
113
- template_manager = TemplateManager()
 
1
+ import json
2
+ import os
3
+ import logging
4
+ from typing import Dict
5
+
6
+ logger = logging.getLogger(__name__)
7
+
8
+ PROMPTS_FILE = "data/prompts.json"
9
+
10
+ DEFAULT_SYSTEM_PROMPT = """You are an expert JEE/NEET educator creating Telegram channel posts.
11
+
12
+ STRICT FORMATTING RULES:
13
+ 1. Use <b>text</b> for bold headers and section titles
14
+ 2. Use <i>text</i> for italics (sparingly)
15
+ 3. Write formulas in plain text using Unicode: Γ— Γ· Ξ” Ξ± Ξ² Ο€ √ β‰ˆ β‰  ≀ β‰₯
16
+ Example: Kp = Kc Γ— (RT)^Ξ”n ← correct
17
+ Never use: $Kp = Kc(RT)^{\\Delta n}$ or backticks for formulas
18
+ 4. Use β€’ for bullet points
19
+ 5. Do NOT use: ##headers, LaTeX, markdown tables, code blocks
20
+ 6. Keep output under 3800 characters
21
+ """
22
+
23
+ DEFAULT_TEMPLATES = {
24
+ "pyq_question": "Generate a realistic Previous Year Question (PYQ) style MCQ for {exam} {year} on the topic \"{chapter}\" from {subject}.",
25
+ "formula_sheet": "Generate a concise 'Formula and Concept Cheat Sheet' for {exam} on the chapter \"{chapter}\" ({subject}).",
26
+ "short_notes": "Create 'Rapid Revision Notes' for {exam} on \"{chapter}\" from {subject}.",
27
+ "motivational": "Write a short, powerful motivational message for an exam aspirant studying {subject}. Topic: {chapter}",
28
+ "concept_recap": "Explain one non-obvious, crucial concept from \"{chapter}\" ({subject}) that often appears in {exam}.",
29
+ "mnemonic": "Create a catchy mnemonic or memory trick to remember a complex set of facts/formulas in \"{chapter}\" ({subject}).",
30
+ "mock_question": "Generate a high-yield 'Mock Challenge' MCQ for {exam} on \"{chapter}\" ({subject}).",
31
+ "mcq_session": """Generate exactly 10 high-quality multiple-choice questions (MCQs) for {exam} on the chapter "{chapter}" ({subject}).
32
+
33
+ IMPORTANT: Return the response ONLY as a JSON array of objects. Do not include any conversational text.
34
+
35
+ Format:
36
+ [
37
+ {{
38
+ "question": "Full question text...",
39
+ "options": ["Option A", "Option B", "Option C", "Option D"],
40
+ "correct_index": 0,
41
+ "explanation": "Why is this the correct answer?"
42
+ }},
43
+ ...
44
+ ]
45
+
46
+ Ensure questions vary in difficulty and cover the entire chapter.
47
+ """
48
+ }
49
+
50
+ class TemplateManager:
51
+ def __init__(self):
52
+ self.data = {
53
+ "system_prompt": DEFAULT_SYSTEM_PROMPT,
54
+ "templates": DEFAULT_TEMPLATES.copy()
55
+ }
56
+ self.load_prompts()
57
+
58
+ def load_prompts(self):
59
+ """Load prompts from Gist (remote) or JSON file (local)."""
60
+ # 1. Try to pull from Gist first
61
+ from content.remote_storage import pull_from_gist
62
+ remote_data = pull_from_gist(os.path.basename(PROMPTS_FILE))
63
+ if remote_data:
64
+ if "system_prompt" in remote_data:
65
+ self.data["system_prompt"] = remote_data["system_prompt"]
66
+ if "templates" in remote_data:
67
+ self.data["templates"].update(remote_data["templates"])
68
+ logger.info(f"[OK] Prompts loaded from Gist")
69
+ # Save locally
70
+ self._save_local()
71
+ return
72
+
73
+ # 2. Fallback to local file
74
+ if not os.path.exists(PROMPTS_FILE):
75
+ return
76
+ try:
77
+ with open(PROMPTS_FILE, "r") as f:
78
+ loaded_data = json.load(f)
79
+ if "system_prompt" in loaded_data:
80
+ self.data["system_prompt"] = loaded_data["system_prompt"]
81
+ if "templates" in loaded_data:
82
+ self.data["templates"].update(loaded_data["templates"])
83
+ logger.info(f"[OK] Prompts loaded from {PROMPTS_FILE}")
84
+ except Exception as e:
85
+ logger.error(f"Error loading prompts: {e}")
86
+
87
+ def _save_local(self):
88
+ """Internal helper to save prompts to local file."""
89
+ try:
90
+ os.makedirs(os.path.dirname(PROMPTS_FILE), exist_ok=True)
91
+ with open(PROMPTS_FILE, "w") as f:
92
+ json.dump(self.data, f, indent=2)
93
+ except Exception as e:
94
+ logger.error(f"[LOCAL PROMPT SAVE ERROR] {e}")
95
+
96
+ def save_prompts(self, data: dict) -> bool:
97
+ """Save prompts locally and to GitHub Gist."""
98
+ self.data = data
99
+ self._save_local()
100
+
101
+ # Push to Gist
102
+ from content.remote_storage import push_to_gist
103
+ push_to_gist(os.path.basename(PROMPTS_FILE), data)
104
+ return True
105
+
106
+ def get_template(self, content_type: str) -> str:
107
+ return self.data.get("templates", {}).get(content_type, DEFAULT_TEMPLATES.get(content_type, ""))
108
+
109
+ @property
110
+ def system_prompt(self) -> str:
111
+ return self.data.get("system_prompt", "")
112
+
113
+ template_manager = TemplateManager()
content/user_registry.py CHANGED
@@ -1,80 +1,80 @@
1
- """
2
- User Registry
3
- Tracks every user who interacts with the bot (DM or group mention).
4
- Stored in data/user_db.json for persistence.
5
- Used by: Broadcast, Doubt Solver
6
- """
7
-
8
- import json
9
- import os
10
- import logging
11
- from threading import Lock
12
- from datetime import datetime
13
-
14
- logger = logging.getLogger(__name__)
15
- _lock = Lock()
16
-
17
- USER_DB_FILE = "data/user_db.json"
18
-
19
-
20
- def _load() -> dict:
21
- if os.path.exists(USER_DB_FILE):
22
- try:
23
- with open(USER_DB_FILE, "r", encoding="utf-8") as f:
24
- return json.load(f)
25
- except Exception as e:
26
- logger.error(f"[UserDB] Load error: {e}")
27
- return {}
28
-
29
-
30
- def _save(db: dict):
31
- try:
32
- os.makedirs(os.path.dirname(USER_DB_FILE), exist_ok=True)
33
- tmp = USER_DB_FILE + ".tmp"
34
- with open(tmp, "w", encoding="utf-8") as f:
35
- json.dump(db, f, indent=2, ensure_ascii=False)
36
- os.replace(tmp, USER_DB_FILE)
37
- except Exception as e:
38
- logger.error(f"[UserDB] Save error: {e}")
39
-
40
-
41
- # Module-level cache
42
- _db = _load()
43
-
44
-
45
- def register_user(user_id: int, first_name: str, username: str = None):
46
- """Register or update a user in the DB."""
47
- with _lock:
48
- uid = str(user_id)
49
- if uid not in _db:
50
- _db[uid] = {
51
- "first_name": first_name,
52
- "username": username or "",
53
- "joined": datetime.now().isoformat(),
54
- "last_seen": datetime.now().isoformat(),
55
- "messages": 0,
56
- }
57
- logger.info(f"[UserDB] New user registered: {first_name} ({user_id})")
58
- else:
59
- _db[uid]["first_name"] = first_name
60
- _db[uid]["username"] = username or _db[uid].get("username", "")
61
- _db[uid]["last_seen"] = datetime.now().isoformat()
62
-
63
- _db[uid]["messages"] = _db[uid].get("messages", 0) + 1
64
- _save(_db)
65
-
66
-
67
- def get_all_user_ids() -> list:
68
- """Return list of all registered user IDs (as integers)."""
69
- with _lock:
70
- return [int(uid) for uid in _db.keys()]
71
-
72
-
73
- def get_user_count() -> int:
74
- with _lock:
75
- return len(_db)
76
-
77
-
78
- def get_all_users() -> dict:
79
- with _lock:
80
- return dict(_db)
 
1
+ """
2
+ User Registry
3
+ Tracks every user who interacts with the bot (DM or group mention).
4
+ Stored in data/user_db.json for persistence.
5
+ Used by: Broadcast, Doubt Solver
6
+ """
7
+
8
+ import json
9
+ import os
10
+ import logging
11
+ from threading import Lock
12
+ from datetime import datetime
13
+
14
+ logger = logging.getLogger(__name__)
15
+ _lock = Lock()
16
+
17
+ USER_DB_FILE = "data/user_db.json"
18
+
19
+
20
+ def _load() -> dict:
21
+ if os.path.exists(USER_DB_FILE):
22
+ try:
23
+ with open(USER_DB_FILE, "r", encoding="utf-8") as f:
24
+ return json.load(f)
25
+ except Exception as e:
26
+ logger.error(f"[UserDB] Load error: {e}")
27
+ return {}
28
+
29
+
30
+ def _save(db: dict):
31
+ try:
32
+ os.makedirs(os.path.dirname(USER_DB_FILE), exist_ok=True)
33
+ tmp = USER_DB_FILE + ".tmp"
34
+ with open(tmp, "w", encoding="utf-8") as f:
35
+ json.dump(db, f, indent=2, ensure_ascii=False)
36
+ os.replace(tmp, USER_DB_FILE)
37
+ except Exception as e:
38
+ logger.error(f"[UserDB] Save error: {e}")
39
+
40
+
41
+ # Module-level cache
42
+ _db = _load()
43
+
44
+
45
+ def register_user(user_id: int, first_name: str, username: str = None):
46
+ """Register or update a user in the DB."""
47
+ with _lock:
48
+ uid = str(user_id)
49
+ if uid not in _db:
50
+ _db[uid] = {
51
+ "first_name": first_name,
52
+ "username": username or "",
53
+ "joined": datetime.now().isoformat(),
54
+ "last_seen": datetime.now().isoformat(),
55
+ "messages": 0,
56
+ }
57
+ logger.info(f"[UserDB] New user registered: {first_name} ({user_id})")
58
+ else:
59
+ _db[uid]["first_name"] = first_name
60
+ _db[uid]["username"] = username or _db[uid].get("username", "")
61
+ _db[uid]["last_seen"] = datetime.now().isoformat()
62
+
63
+ _db[uid]["messages"] = _db[uid].get("messages", 0) + 1
64
+ _save(_db)
65
+
66
+
67
+ def get_all_user_ids() -> list:
68
+ """Return list of all registered user IDs (as integers)."""
69
+ with _lock:
70
+ return [int(uid) for uid in _db.keys()]
71
+
72
+
73
+ def get_user_count() -> int:
74
+ with _lock:
75
+ return len(_db)
76
+
77
+
78
+ def get_all_users() -> dict:
79
+ with _lock:
80
+ return dict(_db)
data/prompts.json CHANGED
@@ -1,13 +1,13 @@
1
- {
2
- "system_prompt": "You are an expert JEE/NEET educator creating Telegram channel posts.\n\nSTRICT FORMATTING RULES:\n1. Use <b>text</b> for bold headers and section titles\n2. Use <i>text</i> for italics (sparingly)\n3. Write formulas in plain text using Unicode: Γ— Γ· Ξ” Ξ± Ξ² Ο€ √ β‰ˆ β‰  ≀ β‰₯\n Example: Kp = Kc Γ— (RT)^Ξ”n ← correct\n Never use: $Kp = Kc(RT)^{\\Delta n}$ or backticks for formulas\n4. Use β€’ for bullet points\n5. Do NOT use: ##headers, LaTeX, markdown tables, code blocks\n6. Keep output under 3800 characters\n",
3
- "templates": {
4
- "pyq_question": "Generate a realistic Previous Year Question (PYQ) style MCQ for {exam} {year} on the topic \"{chapter}\" from {subject}.\n \n Format EXACTLY like this:\n ━━━━━━━━━━━━━━━━━━━━━\n πŸ“… PYQ Style β€” {exam} {year}\n πŸ“– {subject} | {chapter}\n ━━━━━━━━━━━━━━━━━━━━━\n \n ❓ QUESTION:\n [Write the question concisely - MAX 250 characters]\n \n (A) [Plausible distractor 1]\n (B) [Plausible distractor 2]\n (C) [Plausible distractor 3]\n (D) [Correct answer]\n \n ||βœ… ANSWER: (X) β€” [Correct option text]||\n \n πŸ’‘ EXPLANATION:\n [Short 1-line reason - MAX 180 chars]\n 🎯 Difficulty: [Easy/Medium/Hard]\n πŸ“Œ Key Concept: [Main concept tested]",
5
- "formula_sheet": "Generate a concise Formula and Concept Cheat Sheet for {exam} on the chapter \"{chapter}\" ({subject}).\n\nFormat EXACTLY like this (use Telegram-safe formatting only):\n\nπŸ“ *Formula Sheet β€” {chapter}*\nπŸ“˜ {subject} | {exam}\n━━━━━━━━━━━━━━━━━━\n\n*πŸ”‘ Key Formulas:*\nβ€’ [Formula name]: `formula in plain text`\nβ€’ [Formula name]: `formula in plain text`\n(list 4-6 important formulas)\n\n*⚠️ Common Mistakes:*\nβ€’ [Mistake 1]\nβ€’ [Mistake 2]\n\n*πŸ’‘ Pro-Tip:*\n[One powerful exam trick for this chapter]",
6
- "short_notes": "Create Rapid Revision Notes for {exam} on \"{chapter}\" from {subject}.\n\nFormat EXACTLY like this (Telegram-safe formatting only β€” NO ### headers, NO $LaTeX$, NO **double asterisks**):\n\nπŸ“ *Rapid Revision β€” {chapter}*\nπŸ“˜ {subject} | {exam}\n━━━━━━━━━━━━━━━━━━\n\n*🧠 Core Concept:*\n[2-3 lines explaining the main idea in simple language]\n\n*⚑ Must-Remember Facts:*\nβ€’ [Fact 1 with value if applicable]\nβ€’ [Fact 2]\nβ€’ [Fact 3]\nβ€’ [Fact 4]\n\n*πŸ”¬ Exam Application:*\n[How this topic appears in real exam questions β€” 2 lines]",
7
- "motivational": "Write a short, powerful motivational message for an exam aspirant studying {subject}.\nTopic: {chapter}\nStyle: Warm, genuine, relatable. Avoid generic clichΓ©s. Mention that mastering {chapter} is a step toward their goal.\nFormat: Plain text with emojis. NO markdown headers. Use *bold* sparingly for emphasis. Keep it under 300 characters.",
8
- "concept_recap": "Explain one non-obvious, crucial concept from \"{chapter}\" ({subject}) that often appears in {exam}.\n\nFormat EXACTLY like this (Telegram-safe β€” NO ###, NO $LaTeX$, NO **double asterisk**, NO --- dividers):\n\nπŸŒ… *Concept Spotlight β€” {chapter}*\nπŸ“˜ {subject} | {exam}\n━━━━━━━━━━━━━━━━━━\n\n*πŸ’‘ The Hidden Concept:*\n[Name of the concept in *bold*]\n[2-3 lines explaining WHY it works, not just WHAT it is. Use a simple analogy.]\n\n*🎯 Why JEE/NEET Tests This:*\n[1-2 lines on how this appears in exams]\n\n*⚑ Quick Example:*\n[One short example or MCQ-style question testing this concept]\n`Answer: [answer]`\n\n*πŸ“Œ Remember:*\n[One-line takeaway]",
9
- "mnemonic": "Create a catchy mnemonic or memory trick for \"{chapter}\" ({subject}).\n\nFormat EXACTLY like this (Telegram-safe β€” NO ### headers, NO $LaTeX$):\n\n🧠 *Memory Trick β€” {chapter}*\n━━━━━━━━━━━━━━━━━━\n\n*πŸ”€ The Mnemonic:*\n[The mnemonic word/phrase in *bold*]\n\n*πŸ“– What It Stands For:*\nβ€’ [Letter/word] = [meaning]\nβ€’ [Letter/word] = [meaning]\n(list all parts)\n\n*πŸ’‘ How to Use It:*\n[One practical sentence on how this helps in a real question]",
10
- "mock_question": "Generate a high-yield Mock Challenge MCQ for {exam} on \"{chapter}\" ({subject}). Make it slightly harder than a standard PYQ, testing multiple concepts at once.\n\nFormat EXACTLY like this:\n🎯 *Mock Challenge β€” {chapter}*\nπŸ“˜ {subject} | {exam}\n━━━━━━━━━━━━━━━━━━\n\n❓ *QUESTION:*\n[Question text - MAX 280 chars. NO LaTeX. Write math in plain text like `F = qvB`.]\n\n(A) [Option A]\n(B) [Option B]\n(C) [Option C]\n(D) [Option D]\n\n||βœ… *ANSWER: (X)*||\n\nπŸ’‘ *Solution:*\n[Step-by-step solution in 3-4 bullet points using β€’ symbol]\nβ€’ Step 1...\nβ€’ Step 2...\n🎯 Difficulty: Hard",
11
- "mcq_session": "Generate exactly 10 high-quality multiple-choice questions (MCQs) for {exam} on the chapter \"{chapter}\" ({subject}).\n\nIMPORTANT: Return the response ONLY as a JSON array of objects. Do not include any conversational text or markdown code block wrappers.\n\nFormat:\n[\n {{\n \"question\": \"The full question text? (plain text only, no LaTeX)\",\n \"options\": [\"Option A\", \"Option B\", \"Option C\", \"Option D\"],\n \"correct_index\": 0,\n \"explanation\": \"Step-by-step reasoning for the correct answer. Plain text only.\"\n }},\n ...\n]\n\nEnsure all 10 questions are unique and cover different difficulty levels (Easy, Medium, Hard)."
12
- }
13
- }
 
1
+ {
2
+ "system_prompt": "You are an expert JEE/NEET educator creating Telegram channel posts.\n\nSTRICT FORMATTING RULES:\n1. Use <b>text</b> for bold headers and section titles\n2. Use <i>text</i> for italics (sparingly)\n3. Write formulas in plain text using Unicode: Γ— Γ· Ξ” Ξ± Ξ² Ο€ √ β‰ˆ β‰  ≀ β‰₯\n Example: Kp = Kc Γ— (RT)^Ξ”n ← correct\n Never use: $Kp = Kc(RT)^{\\Delta n}$ or backticks for formulas\n4. Use β€’ for bullet points\n5. Do NOT use: ##headers, LaTeX, markdown tables, code blocks\n6. Keep output under 3800 characters\n",
3
+ "templates": {
4
+ "pyq_question": "Generate a realistic Previous Year Question (PYQ) style MCQ for {exam} {year} on the topic \"{chapter}\" from {subject}.\n \n Format EXACTLY like this:\n ━━━━━━━━━━━━━━━━━━━━━\n πŸ“… PYQ Style β€” {exam} {year}\n πŸ“– {subject} | {chapter}\n ━━━━━━━━━━━━━━━━━━━━━\n \n ❓ QUESTION:\n [Write the question concisely - MAX 250 characters]\n \n (A) [Plausible distractor 1]\n (B) [Plausible distractor 2]\n (C) [Plausible distractor 3]\n (D) [Correct answer]\n \n ||βœ… ANSWER: (X) β€” [Correct option text]||\n \n πŸ’‘ EXPLANATION:\n [Short 1-line reason - MAX 180 chars]\n 🎯 Difficulty: [Easy/Medium/Hard]\n πŸ“Œ Key Concept: [Main concept tested]",
5
+ "formula_sheet": "Generate a concise Formula and Concept Cheat Sheet for {exam} on the chapter \"{chapter}\" ({subject}).\n\nFormat EXACTLY like this (use Telegram-safe formatting only):\n\nπŸ“ *Formula Sheet β€” {chapter}*\nπŸ“˜ {subject} | {exam}\n━━━━━━━━━━━━━━━━━━\n\n*πŸ”‘ Key Formulas:*\nβ€’ [Formula name]: `formula in plain text`\nβ€’ [Formula name]: `formula in plain text`\n(list 4-6 important formulas)\n\n*⚠️ Common Mistakes:*\nβ€’ [Mistake 1]\nβ€’ [Mistake 2]\n\n*πŸ’‘ Pro-Tip:*\n[One powerful exam trick for this chapter]",
6
+ "short_notes": "Create Rapid Revision Notes for {exam} on \"{chapter}\" from {subject}.\n\nFormat EXACTLY like this (Telegram-safe formatting only β€” NO ### headers, NO $LaTeX$, NO **double asterisks**):\n\nπŸ“ *Rapid Revision β€” {chapter}*\nπŸ“˜ {subject} | {exam}\n━━━━━━━━━━━━━━━━━━\n\n*🧠 Core Concept:*\n[2-3 lines explaining the main idea in simple language]\n\n*⚑ Must-Remember Facts:*\nβ€’ [Fact 1 with value if applicable]\nβ€’ [Fact 2]\nβ€’ [Fact 3]\nβ€’ [Fact 4]\n\n*πŸ”¬ Exam Application:*\n[How this topic appears in real exam questions β€” 2 lines]",
7
+ "motivational": "Write a short, powerful motivational message for an exam aspirant studying {subject}.\nTopic: {chapter}\nStyle: Warm, genuine, relatable. Avoid generic clichΓ©s. Mention that mastering {chapter} is a step toward their goal.\nFormat: Plain text with emojis. NO markdown headers. Use *bold* sparingly for emphasis. Keep it under 300 characters.",
8
+ "concept_recap": "Explain one non-obvious, crucial concept from \"{chapter}\" ({subject}) that often appears in {exam}.\n\nFormat EXACTLY like this (Telegram-safe β€” NO ###, NO $LaTeX$, NO **double asterisk**, NO --- dividers):\n\nπŸŒ… *Concept Spotlight β€” {chapter}*\nπŸ“˜ {subject} | {exam}\n━━━━━━━━━━━━━━━━━━\n\n*πŸ’‘ The Hidden Concept:*\n[Name of the concept in *bold*]\n[2-3 lines explaining WHY it works, not just WHAT it is. Use a simple analogy.]\n\n*🎯 Why JEE/NEET Tests This:*\n[1-2 lines on how this appears in exams]\n\n*⚑ Quick Example:*\n[One short example or MCQ-style question testing this concept]\n`Answer: [answer]`\n\n*πŸ“Œ Remember:*\n[One-line takeaway]",
9
+ "mnemonic": "Create a catchy mnemonic or memory trick for \"{chapter}\" ({subject}).\n\nFormat EXACTLY like this (Telegram-safe β€” NO ### headers, NO $LaTeX$):\n\n🧠 *Memory Trick β€” {chapter}*\n━━━━━━━━━━━━━━━━━━\n\n*πŸ”€ The Mnemonic:*\n[The mnemonic word/phrase in *bold*]\n\n*πŸ“– What It Stands For:*\nβ€’ [Letter/word] = [meaning]\nβ€’ [Letter/word] = [meaning]\n(list all parts)\n\n*πŸ’‘ How to Use It:*\n[One practical sentence on how this helps in a real question]",
10
+ "mock_question": "Generate a high-yield Mock Challenge MCQ for {exam} on \"{chapter}\" ({subject}). Make it slightly harder than a standard PYQ, testing multiple concepts at once.\n\nFormat EXACTLY like this:\n🎯 *Mock Challenge β€” {chapter}*\nπŸ“˜ {subject} | {exam}\n━━━━━━━━━━━━━━━━━━\n\n❓ *QUESTION:*\n[Question text - MAX 280 chars. NO LaTeX. Write math in plain text like `F = qvB`.]\n\n(A) [Option A]\n(B) [Option B]\n(C) [Option C]\n(D) [Option D]\n\n||βœ… *ANSWER: (X)*||\n\nπŸ’‘ *Solution:*\n[Step-by-step solution in 3-4 bullet points using β€’ symbol]\nβ€’ Step 1...\nβ€’ Step 2...\n🎯 Difficulty: Hard",
11
+ "mcq_session": "Generate exactly 10 high-quality multiple-choice questions (MCQs) for {exam} on the chapter \"{chapter}\" ({subject}).\n\nIMPORTANT: Return the response ONLY as a JSON array of objects. Do not include any conversational text or markdown code block wrappers.\n\nFormat:\n[\n {{\n \"question\": \"The full question text? (plain text only, no LaTeX)\",\n \"options\": [\"Option A\", \"Option B\", \"Option C\", \"Option D\"],\n \"correct_index\": 0,\n \"explanation\": \"Step-by-step reasoning for the correct answer. Plain text only.\"\n }},\n ...\n]\n\nEnsure all 10 questions are unique and cover different difficulty levels (Easy, Medium, Hard)."
12
+ }
13
+ }
data/syllabus.json CHANGED
@@ -1,358 +1,358 @@
1
- {
2
- "JEE_MAINS_2026": {
3
- "Description": "JEE Main 2026 Syllabus (Paper 1: B.E./B.Tech) based on latest NTA/NCERT guidelines.",
4
- "Subjects": {
5
- "Physics": {
6
- "Sections": {
7
- "Section A (Theory)": {
8
- "Class 11": [
9
- "Unit, Dimension, Measurement",
10
- "Physical Quantities and Units",
11
- "Kinematics",
12
- "Laws of Motion",
13
- "Work, Energy and Power",
14
- "Motion of System of Particles and Rigid Body (Rotation)",
15
- "Gravitation",
16
- "Properties of Bulk Matter (Solids, Liquids, Gases)",
17
- "Thermodynamics",
18
- "Behaviour of Perfect Gases and Kinetic Theory of Gases",
19
- "Oscillations and Waves"
20
- ],
21
- "Class 12": [
22
- "Electrostatics",
23
- "Current Electricity",
24
- "Magnetic Effects of Current and Magnetism",
25
- "Electromagnetic Induction and Alternating Currents",
26
- "Electromagnetic Waves",
27
- "Optics",
28
- "Dual Nature of Matter and Radiation",
29
- "Atoms and Nuclei",
30
- "Electronic Devices"
31
- ]
32
- },
33
- "Section B (Practical)": {
34
- "Topics": [
35
- "Experimental Skills (Vernier calipers, screw gauge, simple pendulum, meter bridge, resistance, optics bench)"
36
- ]
37
- }
38
- }
39
- },
40
- "Chemistry": {
41
- "Categories": {
42
- "Physical Chemistry": {
43
- "Class 11": [
44
- "Some Basic Concepts in Chemistry",
45
- "Atomic Structure (Structure of Atom)",
46
- "Chemical Bonding and Molecular Structure",
47
- "Chemical Thermodynamics",
48
- "Solutions",
49
- "Equilibrium",
50
- "Redox Reactions and Electrochemistry"
51
- ],
52
- "Class 12": [
53
- "Chemical Kinetics",
54
- "Surface Chemistry"
55
- ]
56
- },
57
- "Inorganic Chemistry": {
58
- "Class 11": [
59
- "Classification of Elements and Periodicity in Properties",
60
- "Hydrogen",
61
- "s-Block Elements (Alkali and Alkaline Earth Metals)",
62
- "p-Block Elements (Groups 13-18)"
63
- ],
64
- "Class 12": [
65
- "d- and f-Block Elements",
66
- "Coordination Compounds",
67
- "General Principles and Processes of Isolation of Metals",
68
- "Environmental Chemistry"
69
- ]
70
- },
71
- "Organic Chemistry": {
72
- "Class 11": [
73
- "Some Basic Principles of Organic Chemistry",
74
- "Hydrocarbons",
75
- "Organic Compounds Containing Halogens (Haloalkanes and Haloarenes)"
76
- ],
77
- "Class 12": [
78
- "Organic Compounds Containing Oxygen (Alcohols, Phenols, Ethers, Aldehydes, Ketones, Carboxylic Acids)",
79
- "Organic Compounds Containing Nitrogen (Amines)",
80
- "Biomolecules",
81
- "Principles Related to Practical Chemistry",
82
- "Polymers",
83
- "Chemistry in Everyday Life"
84
- ]
85
- }
86
- }
87
- },
88
- "Mathematics": {
89
- "Levels": {
90
- "Class 11": [
91
- "Sets, Relations and Functions",
92
- "Complex Numbers and Quadratic Equations",
93
- "Matrices and Determinants",
94
- "Permutations and Combinations",
95
- "Binomial Theorem and its Simple Applications",
96
- "Sequence and Series",
97
- "Limits, Continuity and Differentiability",
98
- "Integral Calculus",
99
- "Differential Equations",
100
- "Coordinate Geometry (Straight Lines, Circles, Conics)",
101
- "Three Dimensional Geometry",
102
- "Vector Algebra",
103
- "Statistics and Probability (Basic)"
104
- ],
105
- "Class 12": [
106
- "Trigonometry (Identities, Equations, Heights/Distances)",
107
- "Mathematical Reasoning"
108
- ]
109
- }
110
- }
111
- }
112
- },
113
- "JEE_ADVANCED_2026": {
114
- "Description": "JEE Advanced 2026 Syllabus based on IIT Roorkee official guidelines and NCERT Class 11-12 depth.",
115
- "Subjects": {
116
- "Physics": {
117
- "Topics": {
118
- "General Physics": [
119
- "Units, Dimensions, Measurement",
120
- "Experimental Skills"
121
- ],
122
- "Mechanics": [
123
- "Kinematics in 1D/2D/3D",
124
- "Newton's Laws",
125
- "Linear/Angular Momentum",
126
- "Work-Energy",
127
- "Rotational Dynamics",
128
- "Centre of Mass",
129
- "Rigid Body Dynamics",
130
- "Relative Motion",
131
- "Friction",
132
- "Circular Motion"
133
- ],
134
- "Thermal Physics": [
135
- "Thermal Expansion",
136
- "Calorimetry",
137
- "Heat Transfer",
138
- "Kinetic Theory",
139
- "Thermodynamics (Laws, Processes)",
140
- "Ideal Gas Laws"
141
- ],
142
- "Electricity & Magnetism": [
143
- "Electrostatics (Coulomb/Gauss Laws, Potential, Capacitors)",
144
- "Current Electricity",
145
- "Kirchhoff Laws",
146
- "Heating Effects",
147
- "Magnetostatics (Biot-Savart, Ampere)",
148
- "Magnetic Materials",
149
- "EMI (Faraday, Lenz)",
150
- "AC Circuits"
151
- ],
152
- "Electromagnetic Waves": [
153
- "EM Spectrum",
154
- "Properties"
155
- ],
156
- "Optics": [
157
- "Reflection/Refraction",
158
- "Lenses/Mirrors",
159
- "Wave Optics (Interference, Diffraction, Polarization)",
160
- "Optical Instruments"
161
- ],
162
- "Modern Physics": [
163
- "Dual Nature",
164
- "Photoelectric Effect",
165
- "Atomic Structure (Bohr)",
166
- "X-rays",
167
- "Nuclei (Binding Energy, Fission/Fusion)",
168
- "Semiconductors"
169
- ]
170
- }
171
- },
172
- "Chemistry": {
173
- "Categories": {
174
- "Physical Chemistry": [
175
- "Mole Concept",
176
- "Stoichiometry",
177
- "Atomic Structure (Quantum Numbers, Orbitals)",
178
- "Chemical Bonding (VSEPR, MO Theory)",
179
- "Energetics (Enthalpy, Hess Law)",
180
- "Chemical Equilibrium (Kp/Kc, Le Chatelier)",
181
- "Ionic Equilibrium (pH, Buffers)",
182
- "Electrochemistry (Nernst, Conductance)",
183
- "Chemical Kinetics (Orders, Arrhenius)",
184
- "Solid State (Crystal Lattices)",
185
- "Solutions (Raoult, Colligative)",
186
- "Surface Chemistry (Adsorption, Catalysis)",
187
- "Nuclear Chemistry"
188
- ],
189
- "Inorganic Chemistry": [
190
- "Periodic Table (Trends)",
191
- "Chemical Bonding",
192
- "Coordination Compounds (Isomerism, Theories)",
193
- "Hydrogen & s-Block",
194
- "p-Block (Groups 13-18)",
195
- "d/f-Block (Properties, Lanthanoids)",
196
- "Metallurgy",
197
- "Qualitative Analysis"
198
- ],
199
- "Organic Chemistry": [
200
- "GOC (Inductive, Resonance, Hyperconjugation)",
201
- "Isomerism (Structural/Stereo)",
202
- "Hydrocarbons (Alkanes/Alkenes/Alkynes/Arenes)",
203
- "Haloalkanes/Haloarenes",
204
- "Alcohols/Phenols/Ethers",
205
- "Aldehydes/Ketones/Carboxylic Acids",
206
- "Amines",
207
- "Biomolecules (Carbs/Proteins/Nucleic Acids)",
208
- "Polymers",
209
- "Chemistry in Everyday Life",
210
- "Practical Organic Chemistry"
211
- ]
212
- }
213
- },
214
- "Mathematics": {
215
- "Modules": {
216
- "Algebra": [
217
- "Complex Numbers (Polar Form, De Moivre)",
218
- "Quadratic Equations",
219
- "Sequences/Series (AP/GP/Harmonic)",
220
- "Logarithms",
221
- "Permutations/Combinations",
222
- "Binomial Theorem",
223
- "Matrices/Determinants (Inverse, System of Equations)",
224
- "Probability (Bayes, Distributions)"
225
- ],
226
- "Trigonometry": [
227
- "Identities",
228
- "Equations",
229
- "Inverse Functions",
230
- "Heights/Distances",
231
- "Properties of Triangles"
232
- ],
233
- "Analytical Geometry": [
234
- "Cartesian Coordinates",
235
- "Straight Lines",
236
- "Circles",
237
- "Parabola/Ellipse/Hyperbola",
238
- "3D Geometry (Planes, Lines, Sphere)",
239
- "Vectors (Scalar/Vector Products)"
240
- ],
241
- "Calculus": [
242
- "Functions (Even/Odd, Inverse)",
243
- "Limits/Continuity/Differentiability",
244
- "Methods of Differentiation",
245
- "Tangents/Normals",
246
- "Maxima/Minima",
247
- "Indefinite/Definite Integrals (Substitution, Parts, Properties)",
248
- "Area/Volume Applications",
249
- "Differential Equations (Order 1/2)"
250
- ],
251
- "Mathematical Reasoning": [
252
- "Statements",
253
- "Logical Operations",
254
- "Tautology/Contradiction"
255
- ]
256
- }
257
- }
258
- }
259
- },
260
- "NEET_UG_2026": {
261
- "Description": "NEET-UG 2026 Syllabus based on NMC and NTA (neet.nta.nic.in) guidelines, covering NCERT Class 11-12 Biology, Physics, and Chemistry.",
262
- "Subjects": {
263
- "Physics": {
264
- "Units": [
265
- "Physics and Measurement",
266
- "Kinematics",
267
- "Laws of Motion",
268
- "Work, Energy and Power",
269
- "Motion of System of Particles and Rigid Body (Rotational Motion)",
270
- "Gravitation",
271
- "Properties of Bulk Matter (Mechanical Properties of Solids/Fluids)",
272
- "Thermodynamics",
273
- "Behaviour of Perfect Gases and Kinetic Theory of Gases",
274
- "Oscillations and Waves",
275
- "Electrostatics",
276
- "Current Electricity",
277
- "Magnetic Effects of Current and Magnetism",
278
- "Electromagnetic Induction and Alternating Currents",
279
- "Electromagnetic Waves",
280
- "Optics",
281
- "Dual Nature of Matter and Radiation",
282
- "Atoms and Nuclei",
283
- "Electronic Devices"
284
- ]
285
- },
286
- "Chemistry": {
287
- "Categories": {
288
- "Physical Chemistry": [
289
- "Some Basic Concepts of Chemistry",
290
- "Structure of Atom (Atomic Structure)",
291
- "Chemical Thermodynamics",
292
- "Solutions",
293
- "Equilibrium",
294
- "Redox Reactions and Electrochemistry",
295
- "Chemical Kinetics",
296
- "Solid State",
297
- "Surface Chemistry"
298
- ],
299
- "Inorganic Chemistry": [
300
- "Classification of Elements and Periodicity in Properties",
301
- "Chemical Bonding and Molecular Structure",
302
- "States of Matter: Gases and Liquids",
303
- "Hydrogen",
304
- "s-Block Elements",
305
- "p-Block Elements",
306
- "d- and f-Block Elements",
307
- "Coordination Compounds",
308
- "General Principles and Processes of Isolation of Elements",
309
- "Environmental Chemistry"
310
- ],
311
- "Organic Chemistry": [
312
- "Organic Chemistry: Some Basic Principles and Techniques",
313
- "Hydrocarbons",
314
- "Haloalkanes and Haloarenes",
315
- "Alcohols, Phenols and Ethers",
316
- "Aldehydes, Ketones and Carboxylic Acids",
317
- "Organic Compounds Containing Nitrogen (Amines)",
318
- "Biomolecules",
319
- "Polymers",
320
- "Chemistry in Everyday Life"
321
- ]
322
- }
323
- },
324
- "Biology": {
325
- "Categories": {
326
- "Class 11 (Diversity to Physiology)": {
327
- "Botany": [
328
- "Diversity in Living World (The Living World, Biological Classification, Plant Kingdom)",
329
- "Structural Organisation in Plants (Morphology of Flowering Plants, Anatomy of Flowering Plants)",
330
- "Cell: Structure and Function (Cell - The Unit of Life, Biomolecules)",
331
- "Plant Physiology"
332
- ],
333
- "Zoology": [
334
- "Structural Organisation in Animals",
335
- "Human Physiology"
336
- ]
337
- },
338
- "Class 12 (Reproduction to Ecology)": {
339
- "Botany": [
340
- "Reproduction (Sexual Reproduction in Flowering Plants)",
341
- "Genetics and Evolution (Principles of Inheritance and Variation, Molecular Basis of Inheritance)",
342
- "Biology and Human Welfare (Strategies for Enhancement in Food Production, Microbes in Human Welfare)",
343
- "Biotechnology and its Applications",
344
- "Ecology and Environment (Organisms and Populations, Ecosystem, Biodiversity, Environmental Issues)"
345
- ],
346
- "Zoology": [
347
- "Reproduction (Human Reproduction, Reproductive Health)",
348
- "Genetics and Evolution (Evolution)",
349
- "Biology and Human Welfare (Human Health & Diseases)",
350
- "Biotechnology (Biotechnology: Principles & Processes)",
351
- "Ecology and Environment (same as Botany)"
352
- ]
353
- }
354
- }
355
- }
356
- }
357
- }
358
  }
 
1
+ {
2
+ "JEE_MAINS_2026": {
3
+ "Description": "JEE Main 2026 Syllabus (Paper 1: B.E./B.Tech) based on latest NTA/NCERT guidelines.",
4
+ "Subjects": {
5
+ "Physics": {
6
+ "Sections": {
7
+ "Section A (Theory)": {
8
+ "Class 11": [
9
+ "Unit, Dimension, Measurement",
10
+ "Physical Quantities and Units",
11
+ "Kinematics",
12
+ "Laws of Motion",
13
+ "Work, Energy and Power",
14
+ "Motion of System of Particles and Rigid Body (Rotation)",
15
+ "Gravitation",
16
+ "Properties of Bulk Matter (Solids, Liquids, Gases)",
17
+ "Thermodynamics",
18
+ "Behaviour of Perfect Gases and Kinetic Theory of Gases",
19
+ "Oscillations and Waves"
20
+ ],
21
+ "Class 12": [
22
+ "Electrostatics",
23
+ "Current Electricity",
24
+ "Magnetic Effects of Current and Magnetism",
25
+ "Electromagnetic Induction and Alternating Currents",
26
+ "Electromagnetic Waves",
27
+ "Optics",
28
+ "Dual Nature of Matter and Radiation",
29
+ "Atoms and Nuclei",
30
+ "Electronic Devices"
31
+ ]
32
+ },
33
+ "Section B (Practical)": {
34
+ "Topics": [
35
+ "Experimental Skills (Vernier calipers, screw gauge, simple pendulum, meter bridge, resistance, optics bench)"
36
+ ]
37
+ }
38
+ }
39
+ },
40
+ "Chemistry": {
41
+ "Categories": {
42
+ "Physical Chemistry": {
43
+ "Class 11": [
44
+ "Some Basic Concepts in Chemistry",
45
+ "Atomic Structure (Structure of Atom)",
46
+ "Chemical Bonding and Molecular Structure",
47
+ "Chemical Thermodynamics",
48
+ "Solutions",
49
+ "Equilibrium",
50
+ "Redox Reactions and Electrochemistry"
51
+ ],
52
+ "Class 12": [
53
+ "Chemical Kinetics",
54
+ "Surface Chemistry"
55
+ ]
56
+ },
57
+ "Inorganic Chemistry": {
58
+ "Class 11": [
59
+ "Classification of Elements and Periodicity in Properties",
60
+ "Hydrogen",
61
+ "s-Block Elements (Alkali and Alkaline Earth Metals)",
62
+ "p-Block Elements (Groups 13-18)"
63
+ ],
64
+ "Class 12": [
65
+ "d- and f-Block Elements",
66
+ "Coordination Compounds",
67
+ "General Principles and Processes of Isolation of Metals",
68
+ "Environmental Chemistry"
69
+ ]
70
+ },
71
+ "Organic Chemistry": {
72
+ "Class 11": [
73
+ "Some Basic Principles of Organic Chemistry",
74
+ "Hydrocarbons",
75
+ "Organic Compounds Containing Halogens (Haloalkanes and Haloarenes)"
76
+ ],
77
+ "Class 12": [
78
+ "Organic Compounds Containing Oxygen (Alcohols, Phenols, Ethers, Aldehydes, Ketones, Carboxylic Acids)",
79
+ "Organic Compounds Containing Nitrogen (Amines)",
80
+ "Biomolecules",
81
+ "Principles Related to Practical Chemistry",
82
+ "Polymers",
83
+ "Chemistry in Everyday Life"
84
+ ]
85
+ }
86
+ }
87
+ },
88
+ "Mathematics": {
89
+ "Levels": {
90
+ "Class 11": [
91
+ "Sets, Relations and Functions",
92
+ "Complex Numbers and Quadratic Equations",
93
+ "Matrices and Determinants",
94
+ "Permutations and Combinations",
95
+ "Binomial Theorem and its Simple Applications",
96
+ "Sequence and Series",
97
+ "Limits, Continuity and Differentiability",
98
+ "Integral Calculus",
99
+ "Differential Equations",
100
+ "Coordinate Geometry (Straight Lines, Circles, Conics)",
101
+ "Three Dimensional Geometry",
102
+ "Vector Algebra",
103
+ "Statistics and Probability (Basic)"
104
+ ],
105
+ "Class 12": [
106
+ "Trigonometry (Identities, Equations, Heights/Distances)",
107
+ "Mathematical Reasoning"
108
+ ]
109
+ }
110
+ }
111
+ }
112
+ },
113
+ "JEE_ADVANCED_2026": {
114
+ "Description": "JEE Advanced 2026 Syllabus based on IIT Roorkee official guidelines and NCERT Class 11-12 depth.",
115
+ "Subjects": {
116
+ "Physics": {
117
+ "Topics": {
118
+ "General Physics": [
119
+ "Units, Dimensions, Measurement",
120
+ "Experimental Skills"
121
+ ],
122
+ "Mechanics": [
123
+ "Kinematics in 1D/2D/3D",
124
+ "Newton's Laws",
125
+ "Linear/Angular Momentum",
126
+ "Work-Energy",
127
+ "Rotational Dynamics",
128
+ "Centre of Mass",
129
+ "Rigid Body Dynamics",
130
+ "Relative Motion",
131
+ "Friction",
132
+ "Circular Motion"
133
+ ],
134
+ "Thermal Physics": [
135
+ "Thermal Expansion",
136
+ "Calorimetry",
137
+ "Heat Transfer",
138
+ "Kinetic Theory",
139
+ "Thermodynamics (Laws, Processes)",
140
+ "Ideal Gas Laws"
141
+ ],
142
+ "Electricity & Magnetism": [
143
+ "Electrostatics (Coulomb/Gauss Laws, Potential, Capacitors)",
144
+ "Current Electricity",
145
+ "Kirchhoff Laws",
146
+ "Heating Effects",
147
+ "Magnetostatics (Biot-Savart, Ampere)",
148
+ "Magnetic Materials",
149
+ "EMI (Faraday, Lenz)",
150
+ "AC Circuits"
151
+ ],
152
+ "Electromagnetic Waves": [
153
+ "EM Spectrum",
154
+ "Properties"
155
+ ],
156
+ "Optics": [
157
+ "Reflection/Refraction",
158
+ "Lenses/Mirrors",
159
+ "Wave Optics (Interference, Diffraction, Polarization)",
160
+ "Optical Instruments"
161
+ ],
162
+ "Modern Physics": [
163
+ "Dual Nature",
164
+ "Photoelectric Effect",
165
+ "Atomic Structure (Bohr)",
166
+ "X-rays",
167
+ "Nuclei (Binding Energy, Fission/Fusion)",
168
+ "Semiconductors"
169
+ ]
170
+ }
171
+ },
172
+ "Chemistry": {
173
+ "Categories": {
174
+ "Physical Chemistry": [
175
+ "Mole Concept",
176
+ "Stoichiometry",
177
+ "Atomic Structure (Quantum Numbers, Orbitals)",
178
+ "Chemical Bonding (VSEPR, MO Theory)",
179
+ "Energetics (Enthalpy, Hess Law)",
180
+ "Chemical Equilibrium (Kp/Kc, Le Chatelier)",
181
+ "Ionic Equilibrium (pH, Buffers)",
182
+ "Electrochemistry (Nernst, Conductance)",
183
+ "Chemical Kinetics (Orders, Arrhenius)",
184
+ "Solid State (Crystal Lattices)",
185
+ "Solutions (Raoult, Colligative)",
186
+ "Surface Chemistry (Adsorption, Catalysis)",
187
+ "Nuclear Chemistry"
188
+ ],
189
+ "Inorganic Chemistry": [
190
+ "Periodic Table (Trends)",
191
+ "Chemical Bonding",
192
+ "Coordination Compounds (Isomerism, Theories)",
193
+ "Hydrogen & s-Block",
194
+ "p-Block (Groups 13-18)",
195
+ "d/f-Block (Properties, Lanthanoids)",
196
+ "Metallurgy",
197
+ "Qualitative Analysis"
198
+ ],
199
+ "Organic Chemistry": [
200
+ "GOC (Inductive, Resonance, Hyperconjugation)",
201
+ "Isomerism (Structural/Stereo)",
202
+ "Hydrocarbons (Alkanes/Alkenes/Alkynes/Arenes)",
203
+ "Haloalkanes/Haloarenes",
204
+ "Alcohols/Phenols/Ethers",
205
+ "Aldehydes/Ketones/Carboxylic Acids",
206
+ "Amines",
207
+ "Biomolecules (Carbs/Proteins/Nucleic Acids)",
208
+ "Polymers",
209
+ "Chemistry in Everyday Life",
210
+ "Practical Organic Chemistry"
211
+ ]
212
+ }
213
+ },
214
+ "Mathematics": {
215
+ "Modules": {
216
+ "Algebra": [
217
+ "Complex Numbers (Polar Form, De Moivre)",
218
+ "Quadratic Equations",
219
+ "Sequences/Series (AP/GP/Harmonic)",
220
+ "Logarithms",
221
+ "Permutations/Combinations",
222
+ "Binomial Theorem",
223
+ "Matrices/Determinants (Inverse, System of Equations)",
224
+ "Probability (Bayes, Distributions)"
225
+ ],
226
+ "Trigonometry": [
227
+ "Identities",
228
+ "Equations",
229
+ "Inverse Functions",
230
+ "Heights/Distances",
231
+ "Properties of Triangles"
232
+ ],
233
+ "Analytical Geometry": [
234
+ "Cartesian Coordinates",
235
+ "Straight Lines",
236
+ "Circles",
237
+ "Parabola/Ellipse/Hyperbola",
238
+ "3D Geometry (Planes, Lines, Sphere)",
239
+ "Vectors (Scalar/Vector Products)"
240
+ ],
241
+ "Calculus": [
242
+ "Functions (Even/Odd, Inverse)",
243
+ "Limits/Continuity/Differentiability",
244
+ "Methods of Differentiation",
245
+ "Tangents/Normals",
246
+ "Maxima/Minima",
247
+ "Indefinite/Definite Integrals (Substitution, Parts, Properties)",
248
+ "Area/Volume Applications",
249
+ "Differential Equations (Order 1/2)"
250
+ ],
251
+ "Mathematical Reasoning": [
252
+ "Statements",
253
+ "Logical Operations",
254
+ "Tautology/Contradiction"
255
+ ]
256
+ }
257
+ }
258
+ }
259
+ },
260
+ "NEET_UG_2026": {
261
+ "Description": "NEET-UG 2026 Syllabus based on NMC and NTA (neet.nta.nic.in) guidelines, covering NCERT Class 11-12 Biology, Physics, and Chemistry.",
262
+ "Subjects": {
263
+ "Physics": {
264
+ "Units": [
265
+ "Physics and Measurement",
266
+ "Kinematics",
267
+ "Laws of Motion",
268
+ "Work, Energy and Power",
269
+ "Motion of System of Particles and Rigid Body (Rotational Motion)",
270
+ "Gravitation",
271
+ "Properties of Bulk Matter (Mechanical Properties of Solids/Fluids)",
272
+ "Thermodynamics",
273
+ "Behaviour of Perfect Gases and Kinetic Theory of Gases",
274
+ "Oscillations and Waves",
275
+ "Electrostatics",
276
+ "Current Electricity",
277
+ "Magnetic Effects of Current and Magnetism",
278
+ "Electromagnetic Induction and Alternating Currents",
279
+ "Electromagnetic Waves",
280
+ "Optics",
281
+ "Dual Nature of Matter and Radiation",
282
+ "Atoms and Nuclei",
283
+ "Electronic Devices"
284
+ ]
285
+ },
286
+ "Chemistry": {
287
+ "Categories": {
288
+ "Physical Chemistry": [
289
+ "Some Basic Concepts of Chemistry",
290
+ "Structure of Atom (Atomic Structure)",
291
+ "Chemical Thermodynamics",
292
+ "Solutions",
293
+ "Equilibrium",
294
+ "Redox Reactions and Electrochemistry",
295
+ "Chemical Kinetics",
296
+ "Solid State",
297
+ "Surface Chemistry"
298
+ ],
299
+ "Inorganic Chemistry": [
300
+ "Classification of Elements and Periodicity in Properties",
301
+ "Chemical Bonding and Molecular Structure",
302
+ "States of Matter: Gases and Liquids",
303
+ "Hydrogen",
304
+ "s-Block Elements",
305
+ "p-Block Elements",
306
+ "d- and f-Block Elements",
307
+ "Coordination Compounds",
308
+ "General Principles and Processes of Isolation of Elements",
309
+ "Environmental Chemistry"
310
+ ],
311
+ "Organic Chemistry": [
312
+ "Organic Chemistry: Some Basic Principles and Techniques",
313
+ "Hydrocarbons",
314
+ "Haloalkanes and Haloarenes",
315
+ "Alcohols, Phenols and Ethers",
316
+ "Aldehydes, Ketones and Carboxylic Acids",
317
+ "Organic Compounds Containing Nitrogen (Amines)",
318
+ "Biomolecules",
319
+ "Polymers",
320
+ "Chemistry in Everyday Life"
321
+ ]
322
+ }
323
+ },
324
+ "Biology": {
325
+ "Categories": {
326
+ "Class 11 (Diversity to Physiology)": {
327
+ "Botany": [
328
+ "Diversity in Living World (The Living World, Biological Classification, Plant Kingdom)",
329
+ "Structural Organisation in Plants (Morphology of Flowering Plants, Anatomy of Flowering Plants)",
330
+ "Cell: Structure and Function (Cell - The Unit of Life, Biomolecules)",
331
+ "Plant Physiology"
332
+ ],
333
+ "Zoology": [
334
+ "Structural Organisation in Animals",
335
+ "Human Physiology"
336
+ ]
337
+ },
338
+ "Class 12 (Reproduction to Ecology)": {
339
+ "Botany": [
340
+ "Reproduction (Sexual Reproduction in Flowering Plants)",
341
+ "Genetics and Evolution (Principles of Inheritance and Variation, Molecular Basis of Inheritance)",
342
+ "Biology and Human Welfare (Strategies for Enhancement in Food Production, Microbes in Human Welfare)",
343
+ "Biotechnology and its Applications",
344
+ "Ecology and Environment (Organisms and Populations, Ecosystem, Biodiversity, Environmental Issues)"
345
+ ],
346
+ "Zoology": [
347
+ "Reproduction (Human Reproduction, Reproductive Health)",
348
+ "Genetics and Evolution (Evolution)",
349
+ "Biology and Human Welfare (Human Health & Diseases)",
350
+ "Biotechnology (Biotechnology: Principles & Processes)",
351
+ "Ecology and Environment (same as Botany)"
352
+ ]
353
+ }
354
+ }
355
+ }
356
+ }
357
+ }
358
  }
handlers/callbacks.py CHANGED
@@ -191,7 +191,7 @@ async def button_callback(update: Update, context: ContextTypes.DEFAULT_TYPE):
191
  quiz = content["quiz"]
192
  try:
193
  await context.bot.send_message(
194
- chat_id=channel_id, text=content["text"], parse_mode="MarkdownV2"
195
  )
196
  except Exception:
197
  await context.bot.send_message(chat_id=channel_id, text=content["text"])
@@ -204,7 +204,7 @@ async def button_callback(update: Update, context: ContextTypes.DEFAULT_TYPE):
204
  else:
205
  text = content["text"] if isinstance(content, dict) else content
206
  try:
207
- await context.bot.send_message(chat_id=channel_id, text=text, parse_mode="MarkdownV2")
208
  except Exception as md_err:
209
  if "parse" in str(md_err).lower() or "entities" in str(md_err).lower():
210
  await context.bot.send_message(chat_id=channel_id, text=text)
 
191
  quiz = content["quiz"]
192
  try:
193
  await context.bot.send_message(
194
+ chat_id=channel_id, text=content["text"], parse_mode="HTML"
195
  )
196
  except Exception:
197
  await context.bot.send_message(chat_id=channel_id, text=content["text"])
 
204
  else:
205
  text = content["text"] if isinstance(content, dict) else content
206
  try:
207
+ await context.bot.send_message(chat_id=channel_id, text=text, parse_mode="HTML")
208
  except Exception as md_err:
209
  if "parse" in str(md_err).lower() or "entities" in str(md_err).lower():
210
  await context.bot.send_message(chat_id=channel_id, text=text)
handlers/commands.py CHANGED
@@ -462,7 +462,7 @@ async def broadcast_channels_command(update: Update, context: ContextTypes.DEFAU
462
  if not ch_cfg.get("active"): continue
463
  total += 1
464
  try:
465
- await context.bot.send_message(chat_id=ch_cfg["id"], text=msg_text, parse_mode="MarkdownV2")
466
  sent += 1
467
  except Exception as e:
468
  logger.warning(f"Channel Broadcast failed for {ch_key}: {e}")
 
462
  if not ch_cfg.get("active"): continue
463
  total += 1
464
  try:
465
+ await context.bot.send_message(chat_id=ch_cfg["id"], text=msg_text, parse_mode="HTML")
466
  sent += 1
467
  except Exception as e:
468
  logger.warning(f"Channel Broadcast failed for {ch_key}: {e}")
remote_storage.py CHANGED
@@ -1,72 +1,72 @@
1
- import json
2
- import logging
3
- import requests
4
- logger = logging.getLogger(__name__)
5
-
6
- def pull_from_gist(filename: str) -> dict:
7
- """Pull a specific JSON file from the GitHub Gist."""
8
- from config import GIST_ID, GIST_TOKEN
9
- if not GIST_ID or not GIST_TOKEN:
10
- return None
11
-
12
- try:
13
- url = f"https://api.github.com/gists/{GIST_ID}"
14
- headers = {"Authorization": f"token {GIST_TOKEN}"}
15
- resp = requests.get(url, headers=headers, timeout=10)
16
-
17
- if resp.status_code == 200:
18
- gist_data = resp.json()
19
- files = gist_data.get("files", {})
20
- if filename in files:
21
- content = files[filename].get("content", "{}")
22
- logger.info(f"Successfully pulled {filename} from Gist")
23
- return json.loads(content)
24
- elif resp.status_code == 401:
25
- logger.error(f"Gist Pull Failed ({filename}): [401 Unauthorized] Check your GIST_TOKEN.")
26
- elif resp.status_code != 404:
27
- logger.error(f"Failed to pull {filename} from Gist (Status {resp.status_code})")
28
- except Exception as e:
29
- logger.error(f"Error pulling {filename} from Gist: {e}")
30
-
31
- return None
32
-
33
-
34
- def push_to_gist(filename: str, data_dict: dict):
35
- """Push a dictionary to a specific file in the GitHub Gist."""
36
- from config import GIST_ID, GIST_TOKEN
37
- if not GIST_ID or not GIST_TOKEN:
38
- return
39
-
40
- try:
41
- url = f"https://api.github.com/gists/{GIST_ID}"
42
- headers = {"Authorization": f"token {GIST_TOKEN}"}
43
-
44
- content = json.dumps(data_dict, indent=2)
45
- payload = {
46
- "files": {
47
- filename: {
48
- "content": content
49
- }
50
- }
51
- }
52
-
53
- resp = requests.patch(url, headers=headers, json=payload, timeout=10)
54
-
55
- if resp.status_code == 200:
56
- logger.info(f"Successfully pushed {filename} to Gist")
57
- elif resp.status_code == 401:
58
- logger.error(f"Gist Push Failed ({filename}): [401 Unauthorized] Check your GIST_TOKEN.")
59
- else:
60
- logger.error(f"Failed to push {filename} to Gist (Status {resp.status_code})")
61
- except Exception as e:
62
- logger.error(f"Error pushing {filename} to Gist: {e}")
63
-
64
-
65
- # ── Legacy Wrappers (to avoid breaking other files) ───────────────────────────
66
- def pull_history_from_gist() -> dict:
67
- from config import HISTORY_FILE_NAME
68
- return pull_from_gist(HISTORY_FILE_NAME)
69
-
70
- def push_history_to_gist(history_dict: dict):
71
- from config import HISTORY_FILE_NAME
72
- push_to_gist(HISTORY_FILE_NAME, history_dict)
 
1
+ import json
2
+ import logging
3
+ import requests
4
+ logger = logging.getLogger(__name__)
5
+
6
+ def pull_from_gist(filename: str) -> dict:
7
+ """Pull a specific JSON file from the GitHub Gist."""
8
+ from config import GIST_ID, GIST_TOKEN
9
+ if not GIST_ID or not GIST_TOKEN:
10
+ return None
11
+
12
+ try:
13
+ url = f"https://api.github.com/gists/{GIST_ID}"
14
+ headers = {"Authorization": f"token {GIST_TOKEN}"}
15
+ resp = requests.get(url, headers=headers, timeout=10)
16
+
17
+ if resp.status_code == 200:
18
+ gist_data = resp.json()
19
+ files = gist_data.get("files", {})
20
+ if filename in files:
21
+ content = files[filename].get("content", "{}")
22
+ logger.info(f"Successfully pulled {filename} from Gist")
23
+ return json.loads(content)
24
+ elif resp.status_code == 401:
25
+ logger.error(f"Gist Pull Failed ({filename}): [401 Unauthorized] Check your GIST_TOKEN.")
26
+ elif resp.status_code != 404:
27
+ logger.error(f"Failed to pull {filename} from Gist (Status {resp.status_code})")
28
+ except Exception as e:
29
+ logger.error(f"Error pulling {filename} from Gist: {e}")
30
+
31
+ return None
32
+
33
+
34
+ def push_to_gist(filename: str, data_dict: dict):
35
+ """Push a dictionary to a specific file in the GitHub Gist."""
36
+ from config import GIST_ID, GIST_TOKEN
37
+ if not GIST_ID or not GIST_TOKEN:
38
+ return
39
+
40
+ try:
41
+ url = f"https://api.github.com/gists/{GIST_ID}"
42
+ headers = {"Authorization": f"token {GIST_TOKEN}"}
43
+
44
+ content = json.dumps(data_dict, indent=2)
45
+ payload = {
46
+ "files": {
47
+ filename: {
48
+ "content": content
49
+ }
50
+ }
51
+ }
52
+
53
+ resp = requests.patch(url, headers=headers, json=payload, timeout=10)
54
+
55
+ if resp.status_code == 200:
56
+ logger.info(f"Successfully pushed {filename} to Gist")
57
+ elif resp.status_code == 401:
58
+ logger.error(f"Gist Push Failed ({filename}): [401 Unauthorized] Check your GIST_TOKEN.")
59
+ else:
60
+ logger.error(f"Failed to push {filename} to Gist (Status {resp.status_code})")
61
+ except Exception as e:
62
+ logger.error(f"Error pushing {filename} to Gist: {e}")
63
+
64
+
65
+ # ── Legacy Wrappers (to avoid breaking other files) ───────────────────────────
66
+ def pull_history_from_gist() -> dict:
67
+ from config import HISTORY_FILE_NAME
68
+ return pull_from_gist(HISTORY_FILE_NAME)
69
+
70
+ def push_history_to_gist(history_dict: dict):
71
+ from config import HISTORY_FILE_NAME
72
+ push_to_gist(HISTORY_FILE_NAME, history_dict)
requirements.txt CHANGED
@@ -1,7 +1,7 @@
1
- python-telegram-bot>=20.0
2
- apscheduler>=3.10.0
3
- pytz
4
- python-dotenv
5
- requests
6
- fpdf2>=2.7.0
7
- httpx
 
1
+ python-telegram-bot>=20.0
2
+ apscheduler>=3.10.0
3
+ pytz
4
+ python-dotenv
5
+ requests
6
+ fpdf2>=2.7.0
7
+ httpx
scheduler/job_scheduler.py CHANGED
@@ -52,15 +52,15 @@ async def _safe_send_message(app: Application, chat_id, text: str, **kwargs):
52
  except Exception as e:
53
  err = str(e).lower()
54
  if "can't parse" in err or "entities" in err or "parse" in err:
55
- logger.warning(f"[MarkdownV2 Parse Error] Chat {chat_id}: {str(e)[:200]}")
56
- logger.warning(f"[MarkdownV2] Problematic text (first 300 chars): {text[:300]}")
57
- logger.warning(f"[MarkdownV2] Retrying as plain text...")
58
  plain_kwargs = {k: v for k, v in kwargs.items() if k != "parse_mode"}
59
  try:
60
  await app.bot.send_message(chat_id=chat_id, text=text, **plain_kwargs)
61
- logger.warning(f"[MarkdownV2] Fallback to plain text succeeded")
62
  except Exception as fallback_err:
63
- logger.error(f"[MarkdownV2] Even plain text failed: {fallback_err}")
64
  raise
65
  else:
66
  raise
@@ -97,7 +97,7 @@ async def post_content(app: Application, content_type: str, channel_key: str,
97
  quiz = content["quiz"]
98
  await _safe_send_message(
99
  app, channel_id, content["text"],
100
- parse_mode="MarkdownV2"
101
  )
102
  try:
103
  poll = await app.bot.send_poll(
@@ -129,7 +129,7 @@ async def post_content(app: Application, content_type: str, channel_key: str,
129
  text = content["text"] if isinstance(content, dict) else str(content)
130
  await _safe_send_message(
131
  app, channel_id, text,
132
- parse_mode="MarkdownV2"
133
  )
134
 
135
  logger.info(f"[OK] Posted [{content_type}] β†’ [{ch_label}]")
@@ -178,9 +178,9 @@ async def post_mcq_session(app: Application, channel_key: str):
178
  try:
179
  await _safe_send_message(
180
  app, channel_id,
181
- text=(f"πŸ“š *Today\\'s Topic\\: {chapter}*\nπŸ”¬ {subject}\n"
182
- f"⏳ {total} MCQs \\| \\~{delay_min}\\-{delay_max}s gaps\nπŸ“… Get ready\\!"),
183
- parse_mode="MarkdownV2", reply_markup=markup
184
  )
185
  except Exception as e:
186
  logger.error(f"[MCQ] Announcement failed: {e}"); return
@@ -223,12 +223,12 @@ async def post_mcq_session(app: Application, channel_key: str):
223
  try:
224
  await _safe_send_message(
225
  app, channel_id,
226
- text=(f"🌟 *MCQ Session Complete\\!*\n"
227
  f"━━━━━━━━━━━━━━━━━━\n"
228
- f"πŸ“Š Score yourself out of *{total}* in the comments below\\! 🎯\n\n"
229
- f"✨ *Keep learning, keep growing.*\n\n"
230
- f"πŸš€ Join our main community\\: @xcrazylearners"),
231
- parse_mode="MarkdownV2"
232
  )
233
  await _notify_admins(app, f"βœ… MCQ Session done β€” {total} polls for *{cfg.get('label')}*")
234
  except Exception as e:
@@ -248,7 +248,7 @@ async def check_nta_updates(app: Application):
248
  for ch_key, ch_cfg in config_manager.channels.items():
249
  if ch_cfg.get("active"):
250
  try:
251
- await _safe_send_message(app, ch_cfg["id"], msg, parse_mode="MarkdownV2")
252
  except Exception as e:
253
  logger.warning(f"Failed to post news bundle to {ch_key}: {e}")
254
 
@@ -267,14 +267,14 @@ async def reset_leaderboard_job(app: Application):
267
  from content.database import get_top_students
268
  top = get_top_students(ch_cfg["id"], limit=3)
269
  if top:
270
- text = "πŸ† *Weekly Champions Hall of Fame*\n━━━━━━━━━━━━━━━━━━\n"
271
  medals = ["πŸ₯‡", "πŸ₯ˆ", "πŸ₯‰"]
272
  for i, (uname, fname, score) in enumerate(top):
273
  name = f"@{uname}" if uname != "Anonymous" else fname
274
- text += f"{medals[i]} *{name}* β€” {score} pts\n"
275
 
276
- text += "\nπŸ”₯ *New week starts now!* Can you top the list?\nπŸš€ @xcrazylearners"
277
- await _safe_send_message(app, ch_cfg["id"], text, parse_mode="MarkdownV2")
278
 
279
  clear_weekly_scores()
280
  await _notify_admins(app, "πŸ“Š Weekly leaderboard reset complete.")
@@ -291,10 +291,10 @@ async def post_weekly_digest(app: Application, channel_key: str):
291
  pdf_path = create_digest_pdf(ch_label, f"Weekly {title}", archive)
292
  if pdf_path:
293
  caption = (
294
- f"πŸ“š *Weekly {title}* β€” {ch_label}\n\n"
295
  f"Your complete week of {title.lower()} in one PDF.\n"
296
  f"All chapters β€’ All subjects β€’ Beautifully formatted\n\n"
297
- f"πŸ”₯ *CrazyLearners* | [Join Now](https://t.me/xcrazylearners)\n"
298
  f"Daily Notes | PYQs | MCQ Sessions | Formula Sheets"
299
  )
300
  with open(pdf_path, "rb") as pdf_file:
@@ -303,7 +303,7 @@ async def post_weekly_digest(app: Application, channel_key: str):
303
  document=pdf_file,
304
  filename=f"CrazyLearners_{title.replace(' ', '_')}_{ch_label}.pdf",
305
  caption=caption,
306
- parse_mode="MarkdownV2"
307
  )
308
  clear_weekly_archive(channel_key)
309
  await _notify_admins(app, f"πŸ“„ Weekly digest sent to *{ch_label}*.")
 
52
  except Exception as e:
53
  err = str(e).lower()
54
  if "can't parse" in err or "entities" in err or "parse" in err:
55
+ logger.warning(f"[HTML Parse Error] Chat {chat_id}: {str(e)[:200]}")
56
+ logger.warning(f"[HTML] Problematic text (first 300 chars): {text[:300]}")
57
+ logger.warning(f"[HTML] Retrying as plain text...")
58
  plain_kwargs = {k: v for k, v in kwargs.items() if k != "parse_mode"}
59
  try:
60
  await app.bot.send_message(chat_id=chat_id, text=text, **plain_kwargs)
61
+ logger.warning(f"[HTML] Fallback to plain text succeeded")
62
  except Exception as fallback_err:
63
+ logger.error(f"[HTML] Even plain text failed: {fallback_err}")
64
  raise
65
  else:
66
  raise
 
97
  quiz = content["quiz"]
98
  await _safe_send_message(
99
  app, channel_id, content["text"],
100
+ parse_mode="HTML"
101
  )
102
  try:
103
  poll = await app.bot.send_poll(
 
129
  text = content["text"] if isinstance(content, dict) else str(content)
130
  await _safe_send_message(
131
  app, channel_id, text,
132
+ parse_mode="HTML"
133
  )
134
 
135
  logger.info(f"[OK] Posted [{content_type}] β†’ [{ch_label}]")
 
178
  try:
179
  await _safe_send_message(
180
  app, channel_id,
181
+ text=(f"πŸ“š <b>Today's Topic: {chapter}</b>\nπŸ”¬ {subject}\n"
182
+ f"⏳ {total} MCQs | ~{delay_min}-{delay_max}s gaps\nπŸ“… Get ready!"),
183
+ parse_mode="HTML", reply_markup=markup
184
  )
185
  except Exception as e:
186
  logger.error(f"[MCQ] Announcement failed: {e}"); return
 
223
  try:
224
  await _safe_send_message(
225
  app, channel_id,
226
+ text=(f"🌟 <b>MCQ Session Complete!</b>\n"
227
  f"━━━━━━━━━━━━━━━━━━\n"
228
+ f"πŸ“Š Score yourself out of <b>{total}</b> in the comments below! 🎯\n\n"
229
+ f"✨ <b>Keep learning, keep growing.</b>\n\n"
230
+ f"πŸš€ Join our main community: @xcrazylearners"),
231
+ parse_mode="HTML"
232
  )
233
  await _notify_admins(app, f"βœ… MCQ Session done β€” {total} polls for *{cfg.get('label')}*")
234
  except Exception as e:
 
248
  for ch_key, ch_cfg in config_manager.channels.items():
249
  if ch_cfg.get("active"):
250
  try:
251
+ await _safe_send_message(app, ch_cfg["id"], msg, parse_mode="HTML")
252
  except Exception as e:
253
  logger.warning(f"Failed to post news bundle to {ch_key}: {e}")
254
 
 
267
  from content.database import get_top_students
268
  top = get_top_students(ch_cfg["id"], limit=3)
269
  if top:
270
+ text = "πŸ† <b>Weekly Champions Hall of Fame</b>\n━━━━━━━━━━━━━━━━━━\n"
271
  medals = ["πŸ₯‡", "πŸ₯ˆ", "πŸ₯‰"]
272
  for i, (uname, fname, score) in enumerate(top):
273
  name = f"@{uname}" if uname != "Anonymous" else fname
274
+ text += f"{medals[i]} <b>{name}</b> β€” {score} pts\n"
275
 
276
+ text += "\nπŸ”₯ <b>New week starts now!</b> Can you top the list?\nπŸš€ @xcrazylearners"
277
+ await _safe_send_message(app, ch_cfg["id"], text, parse_mode="HTML")
278
 
279
  clear_weekly_scores()
280
  await _notify_admins(app, "πŸ“Š Weekly leaderboard reset complete.")
 
291
  pdf_path = create_digest_pdf(ch_label, f"Weekly {title}", archive)
292
  if pdf_path:
293
  caption = (
294
+ f"πŸ“š <b>Weekly {title}</b> β€” {ch_label}\n\n"
295
  f"Your complete week of {title.lower()} in one PDF.\n"
296
  f"All chapters β€’ All subjects β€’ Beautifully formatted\n\n"
297
+ f"πŸ”₯ <b>CrazyLearners</b> | <a href='https://t.me/xcrazylearners'>Join Now</a>\n"
298
  f"Daily Notes | PYQs | MCQ Sessions | Formula Sheets"
299
  )
300
  with open(pdf_path, "rb") as pdf_file:
 
303
  document=pdf_file,
304
  filename=f"CrazyLearners_{title.replace(' ', '_')}_{ch_label}.pdf",
305
  caption=caption,
306
+ parse_mode="HTML"
307
  )
308
  clear_weekly_archive(channel_key)
309
  await _notify_admins(app, f"πŸ“„ Weekly digest sent to *{ch_label}*.")
web_app/index.html CHANGED
@@ -1,466 +1,466 @@
1
- <!DOCTYPE html>
2
- <html lang="en">
3
- <head>
4
- <meta charset="UTF-8"/>
5
- <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"/>
6
- <title>CrazyLearners Bot Dashboard</title>
7
- <script src="https://telegram.org/js/telegram-web-app.js"></script>
8
- <style>
9
- :root {
10
- --bg: #0f0f1a;
11
- --card: #1a1a2e;
12
- --border: #2a2a4a;
13
- --accent: #7c3aed;
14
- --accent2: #06b6d4;
15
- --green: #22c55e;
16
- --red: #ef4444;
17
- --yellow: #f59e0b;
18
- --text: #e2e8f0;
19
- --muted: #64748b;
20
- --radius: 12px;
21
- }
22
- * { box-sizing: border-box; margin: 0; padding: 0; }
23
- body {
24
- background: var(--bg);
25
- color: var(--text);
26
- font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
27
- min-height: 100vh;
28
- padding-bottom: 30px;
29
- }
30
-
31
- /* ── Header ── */
32
- .header {
33
- background: linear-gradient(135deg, #1e1b4b 0%, #312e81 50%, #1e3a5f 100%);
34
- padding: 20px 16px 16px;
35
- text-align: center;
36
- border-bottom: 1px solid var(--border);
37
- }
38
- .header h1 { font-size: 20px; font-weight: 700; letter-spacing: -0.3px; }
39
- .header h1 span { color: var(--accent2); }
40
- .header p { font-size: 12px; color: var(--muted); margin-top: 4px; }
41
- .status-dot {
42
- display: inline-block; width: 8px; height: 8px;
43
- background: var(--green); border-radius: 50%;
44
- margin-right: 5px; animation: pulse 2s infinite;
45
- }
46
- @keyframes pulse {
47
- 0%, 100% { opacity: 1; } 50% { opacity: 0.4; }
48
- }
49
-
50
- /* ── Tabs ── */
51
- .tabs {
52
- display: flex; background: var(--card);
53
- border-bottom: 1px solid var(--border);
54
- overflow-x: auto; scrollbar-width: none;
55
- }
56
- .tabs::-webkit-scrollbar { display: none; }
57
- .tab {
58
- flex: 1; min-width: 80px; padding: 12px 8px; text-align: center;
59
- font-size: 12px; font-weight: 600; color: var(--muted);
60
- cursor: pointer; border-bottom: 2px solid transparent;
61
- transition: all 0.2s; white-space: nowrap;
62
- }
63
- .tab.active { color: var(--accent2); border-bottom-color: var(--accent2); }
64
-
65
- /* ── Sections ── */
66
- .section { display: none; padding: 16px; }
67
- .section.active { display: block; }
68
-
69
- /* ── Cards ── */
70
- .card {
71
- background: var(--card); border-radius: var(--radius);
72
- border: 1px solid var(--border); margin-bottom: 12px; overflow: hidden;
73
- }
74
- .card-header {
75
- display: flex; align-items: center; justify-content: space-between;
76
- padding: 14px 16px; border-bottom: 1px solid var(--border);
77
- cursor: pointer;
78
- }
79
- .card-header .title { font-weight: 700; font-size: 14px; }
80
- .card-header .subtitle { font-size: 11px; color: var(--muted); margin-top: 2px; }
81
- .card-header .badge {
82
- font-size: 10px; padding: 3px 8px; border-radius: 20px;
83
- font-weight: 600;
84
- }
85
- .badge-active { background: #14532d; color: var(--green); }
86
- .badge-paused { background: #7c2020; color: var(--red); }
87
-
88
- /* ── Content Type Rows ── */
89
- .ct-list { padding: 4px 0; }
90
- .ct-row {
91
- display: flex; align-items: center; justify-content: space-between;
92
- padding: 10px 16px; border-bottom: 1px solid var(--border);
93
- transition: background 0.15s;
94
- }
95
- .ct-row:last-child { border-bottom: none; }
96
- .ct-row:active { background: rgba(124,58,237,0.08); }
97
- .ct-info { flex: 1; }
98
- .ct-name { font-size: 13px; font-weight: 500; }
99
- .ct-time { font-size: 11px; color: var(--muted); margin-top: 2px; }
100
-
101
- /* ── Toggle Switch ── */
102
- .toggle {
103
- position: relative; width: 44px; height: 24px; flex-shrink: 0;
104
- }
105
- .toggle input { opacity: 0; width: 0; height: 0; }
106
- .toggle-track {
107
- position: absolute; top: 0; left: 0; right: 0; bottom: 0;
108
- background: #374151; border-radius: 12px; cursor: pointer;
109
- transition: background 0.25s;
110
- }
111
- .toggle-track::before {
112
- content: ""; position: absolute;
113
- width: 18px; height: 18px; border-radius: 50%;
114
- background: white; top: 3px; left: 3px;
115
- transition: transform 0.25s;
116
- box-shadow: 0 1px 3px rgba(0,0,0,0.4);
117
- }
118
- .toggle input:checked + .toggle-track { background: var(--accent); }
119
- .toggle input:checked + .toggle-track::before { transform: translateX(20px); }
120
- .toggle.loading .toggle-track { opacity: 0.5; pointer-events: none; }
121
-
122
- /* ── Stats Grid ── */
123
- .stats-grid {
124
- display: grid; grid-template-columns: repeat(2, 1fr); gap: 10px; margin-bottom: 14px;
125
- }
126
- .stat-card {
127
- background: var(--card); border: 1px solid var(--border);
128
- border-radius: var(--radius); padding: 14px; text-align: center;
129
- }
130
- .stat-value { font-size: 28px; font-weight: 800; }
131
- .stat-label { font-size: 11px; color: var(--muted); margin-top: 4px; }
132
- .stat-card.accent { border-color: var(--accent); }
133
- .stat-card.accent2 { border-color: var(--accent2); }
134
- .stat-card.green { border-color: var(--green); }
135
- .stat-card.yellow { border-color: var(--yellow); }
136
-
137
- /* ── Schedule Table ── */
138
- .sched-row {
139
- display: flex; align-items: center; padding: 10px 16px;
140
- border-bottom: 1px solid var(--border);
141
- }
142
- .sched-row:last-child { border-bottom: none; }
143
- .sched-time {
144
- font-size: 13px; font-weight: 700; color: var(--accent2);
145
- width: 52px; flex-shrink: 0;
146
- }
147
- .sched-label { font-size: 13px; flex: 1; }
148
- .sched-channels { font-size: 10px; color: var(--muted); }
149
-
150
- /* ── Loading / Error ── */
151
- .loading-text { text-align: center; color: var(--muted); padding: 40px; font-size: 14px; }
152
- .spinner {
153
- width: 24px; height: 24px; border: 3px solid var(--border);
154
- border-top-color: var(--accent2); border-radius: 50%;
155
- animation: spin 0.8s linear infinite; margin: 0 auto 12px;
156
- }
157
- @keyframes spin { to { transform: rotate(360deg); } }
158
-
159
- /* ── Toast ── */
160
- .toast {
161
- position: fixed; bottom: 20px; left: 50%; transform: translateX(-50%);
162
- background: #1e293b; border: 1px solid var(--border);
163
- color: var(--text); padding: 10px 18px; border-radius: 8px;
164
- font-size: 13px; opacity: 0; transition: opacity 0.3s;
165
- pointer-events: none; z-index: 999; white-space: nowrap;
166
- }
167
- .toast.show { opacity: 1; }
168
-
169
- /* ── Expand arrow ── */
170
- .arrow { transition: transform 0.2s; font-size: 12px; color: var(--muted); }
171
- .arrow.open { transform: rotate(180deg); }
172
- </style>
173
- </head>
174
- <body>
175
-
176
- <div class="header">
177
- <h1>πŸŽ“ <span>CrazyLearners</span> Bot</h1>
178
- <p><span class="status-dot"></span>Live Dashboard</p>
179
- </div>
180
-
181
- <div class="tabs">
182
- <div class="tab active" onclick="switchTab('channels')">πŸ“‘ Channels</div>
183
- <div class="tab" onclick="switchTab('schedule')">πŸ• Schedule</div>
184
- <div class="tab" onclick="switchTab('stats')">πŸ“Š Stats</div>
185
- </div>
186
-
187
- <!-- CHANNELS TAB -->
188
- <div id="tab-channels" class="section active">
189
- <div id="channels-content" class="loading-text">
190
- <div class="spinner"></div>Loading channels...
191
- </div>
192
- </div>
193
-
194
- <!-- SCHEDULE TAB -->
195
- <div id="tab-schedule" class="section">
196
- <div id="schedule-content" class="loading-text">
197
- <div class="spinner"></div>Loading schedule...
198
- </div>
199
- </div>
200
-
201
- <!-- STATS TAB -->
202
- <div id="tab-stats" class="section">
203
- <div id="stats-content" class="loading-text">
204
- <div class="spinner"></div>Loading stats...
205
- </div>
206
- </div>
207
-
208
- <div class="toast" id="toast"></div>
209
-
210
- <script>
211
- // ── API base (bot runs on HF Space) ──
212
- const API_BASE = 'https://h3y-sam-telegram-bot.hf.space';
213
-
214
- // ── Telegram Mini App init ──
215
- const tg = window.Telegram?.WebApp;
216
- if (tg) { tg.ready(); tg.expand(); }
217
-
218
- // ── Content type metadata ──
219
- const CT_LABELS = {
220
- pyq_question: "πŸ“… PYQ Question",
221
- formula_sheet: "πŸ“ Formula Sheet",
222
- short_notes: "πŸ“ Short Notes",
223
- mnemonic: "🧠 Memory Tricks",
224
- concept_recap: "πŸŒ… Concept Recap",
225
- mock_question: "🎯 Daily Mock",
226
- motivational: "πŸŒ™ Night Motivation",
227
- mcq_session: "πŸ§ͺ MCQ Poll Session",
228
- };
229
-
230
- const CT_TIMES = {
231
- pyq_question: "7:00 AM",
232
- formula_sheet: "9:00 AM",
233
- short_notes: "12:00 PM",
234
- mnemonic: "3:00 PM",
235
- concept_recap: "6:00 PM",
236
- mock_question: "8:00 PM",
237
- motivational: "10:00 PM",
238
- mcq_session: "8:00 PM",
239
- };
240
-
241
- let state = null;
242
- let openChannels = {};
243
-
244
- // ── Fetch data from API ──
245
- async function fetchStatus() {
246
- try {
247
- const r = await fetch(`${API_BASE}/api/status`);
248
- if (!r.ok) throw new Error('API error');
249
- return await r.json();
250
- } catch (e) {
251
- return null;
252
- }
253
- }
254
-
255
- async function toggleContentType(chKey, ct, el) {
256
- el.classList.add('loading');
257
- try {
258
- const r = await fetch(`${API_BASE}/api/toggle/${chKey}/${ct}`, { method: 'POST' });
259
- const d = await r.json();
260
- const enabled = d.enabled;
261
- el.querySelector('input').checked = enabled;
262
- showToast(enabled ? `βœ… ${CT_LABELS[ct] || ct} enabled` : `⏸️ ${CT_LABELS[ct] || ct} paused`);
263
- // Update state
264
- if (state?.channels?.[chKey]) {
265
- if (!state.channels[chKey].disabled_content_types) state.channels[chKey].disabled_content_types = [];
266
- if (enabled) {
267
- state.channels[chKey].disabled_content_types = state.channels[chKey].disabled_content_types.filter(x => x !== ct);
268
- } else {
269
- if (!state.channels[chKey].disabled_content_types.includes(ct))
270
- state.channels[chKey].disabled_content_types.push(ct);
271
- }
272
- }
273
- } catch(e) {
274
- showToast('❌ Failed β€” check bot logs');
275
- }
276
- el.classList.remove('loading');
277
- }
278
-
279
- async function toggleChannel(chKey, btn) {
280
- btn.disabled = true;
281
- try {
282
- const r = await fetch(`${API_BASE}/api/toggle-channel/${chKey}`, { method: 'POST' });
283
- const d = await r.json();
284
- showToast(d.active ? `βœ… ${d.label} resumed` : `⏸️ ${d.label} paused`);
285
- renderChannels(); // re-render
286
- } catch(e) {
287
- showToast('❌ Failed');
288
- }
289
- btn.disabled = false;
290
- }
291
-
292
- // ── Render: Channels ──
293
- function renderChannels() {
294
- const el = document.getElementById('channels-content');
295
- if (!state) { el.innerHTML = '<p class="loading-text">⚠️ Could not load data. Is the bot running?</p>'; return; }
296
-
297
- const channels = state.channels || {};
298
- let html = '';
299
- for (const [key, cfg] of Object.entries(channels)) {
300
- const active = cfg.active !== false;
301
- const disabled = cfg.disabled_content_types || [];
302
- const mcqOnly = disabled.length >= 6;
303
- const open = openChannels[key] || false;
304
-
305
- html += `
306
- <div class="card">
307
- <div class="card-header" onclick="toggleOpen('${key}')">
308
- <div>
309
- <div class="title">${cfg.label || key}</div>
310
- <div class="subtitle">${cfg.id || ''} Β· ${mcqOnly ? 'MCQ Only' : 'Full Content'}</div>
311
- </div>
312
- <div style="display:flex;align-items:center;gap:8px">
313
- <span class="badge ${active ? 'badge-active' : 'badge-paused'}">${active ? 'Active' : 'Paused'}</span>
314
- <span class="arrow ${open ? 'open' : ''}" id="arrow-${key}">β–Ό</span>
315
- </div>
316
- </div>
317
- ${open ? `
318
- <div class="ct-list">
319
- ${Object.entries(CT_LABELS).map(([ct, label]) => {
320
- const enabled = !disabled.includes(ct);
321
- return `
322
- <div class="ct-row">
323
- <div class="ct-info">
324
- <div class="ct-name">${label}</div>
325
- <div class="ct-time">${CT_TIMES[ct] || 'β€”'} IST</div>
326
- </div>
327
- <label class="toggle" id="toggle-${key}-${ct}">
328
- <input type="checkbox" ${enabled ? 'checked' : ''}
329
- onchange="toggleContentType('${key}','${ct}',document.getElementById('toggle-${key}-${ct}'))">
330
- <div class="toggle-track"></div>
331
- </label>
332
- </div>`;
333
- }).join('')}
334
- <div style="padding:12px 16px">
335
- <button onclick="toggleChannel('${key}',this)"
336
- style="width:100%;padding:10px;border-radius:8px;border:1px solid var(--border);
337
- background:${active ? '#7c2020' : '#14532d'};color:white;font-weight:600;
338
- cursor:pointer;font-size:13px">
339
- ${active ? '⏸️ Pause All Posts' : '▢️ Resume All Posts'}
340
- </button>
341
- </div>
342
- </div>` : ''}
343
- </div>`;
344
- }
345
- el.innerHTML = html;
346
- }
347
-
348
- function toggleOpen(key) {
349
- openChannels[key] = !openChannels[key];
350
- renderChannels();
351
- }
352
-
353
- // ── Render: Schedule ──
354
- function renderSchedule() {
355
- const el = document.getElementById('schedule-content');
356
- if (!state) { el.innerHTML = '<p class="loading-text">⚠️ No data.</p>'; return; }
357
-
358
- const schedule = state.schedule || {};
359
- const channels = state.channels || {};
360
- const rows = Object.entries(schedule)
361
- .sort((a,b) => (a[1].hour*60+a[1].minute) - (b[1].hour*60+b[1].minute));
362
-
363
- let html = '<div class="card"><div style="padding:4px 0">';
364
- for (const [ct, timing] of rows) {
365
- const h = String(timing.hour).padStart(2,'0');
366
- const m = String(timing.minute).padStart(2,'0');
367
- const activeChans = Object.entries(channels)
368
- .filter(([,c]) => c.active && !(c.disabled_content_types||[]).includes(ct))
369
- .map(([,c]) => c.label?.split(' ')[0]).join(', ');
370
- html += `
371
- <div class="sched-row">
372
- <div class="sched-time">${h}:${m}</div>
373
- <div>
374
- <div class="sched-label">${CT_LABELS[ct] || ct}</div>
375
- <div class="sched-channels">${activeChans || 'β€”'}</div>
376
- </div>
377
- </div>`;
378
- }
379
- html += '</div></div>';
380
- el.innerHTML = html;
381
- }
382
-
383
- // ── Render: Stats ──
384
- function renderStats() {
385
- const el = document.getElementById('stats-content');
386
- if (!state) { el.innerHTML = '<p class="loading-text">⚠️ No data.</p>'; return; }
387
-
388
- const channels = state.channels || {};
389
- const total = Object.keys(channels).length;
390
- const active = Object.values(channels).filter(c => c.active).length;
391
- const jobs = state.total_jobs || 0;
392
- const users = state.user_count || 0;
393
-
394
- el.innerHTML = `
395
- <div class="stats-grid">
396
- <div class="stat-card accent">
397
- <div class="stat-value">${active}/${total}</div>
398
- <div class="stat-label">Active Channels</div>
399
- </div>
400
- <div class="stat-card accent2">
401
- <div class="stat-value">${jobs}</div>
402
- <div class="stat-label">Scheduled Jobs</div>
403
- </div>
404
- <div class="stat-card green">
405
- <div class="stat-value">${users}</div>
406
- <div class="stat-label">DM Users</div>
407
- </div>
408
- <div class="stat-card yellow">
409
- <div class="stat-value">${Object.keys(state.schedule||{}).length}</div>
410
- <div class="stat-label">Content Types</div>
411
- </div>
412
- </div>
413
- <div class="card">
414
- <div style="padding:14px 16px;border-bottom:1px solid var(--border);font-weight:700;font-size:13px">
415
- πŸ“‘ Channel Overview
416
- </div>
417
- ${Object.entries(channels).map(([key, cfg]) => {
418
- const disabled = cfg.disabled_content_types || [];
419
- const enabled = Object.keys(CT_LABELS).filter(ct => !disabled.includes(ct));
420
- return `
421
- <div class="sched-row">
422
- <div style="flex:1">
423
- <div class="sched-label">${cfg.label || key}</div>
424
- <div class="sched-channels">${enabled.length} active types Β· ${cfg.id}</div>
425
- </div>
426
- <span class="badge ${cfg.active ? 'badge-active':'badge-paused'}">${cfg.active ? 'On':'Off'}</span>
427
- </div>`;
428
- }).join('')}
429
- </div>`;
430
- }
431
-
432
- // ── Tab switch ──
433
- function switchTab(name) {
434
- document.querySelectorAll('.tab').forEach((t,i) => {
435
- const names = ['channels','schedule','stats'];
436
- t.classList.toggle('active', names[i] === name);
437
- });
438
- document.querySelectorAll('.section').forEach(s => s.classList.remove('active'));
439
- document.getElementById(`tab-${name}`).classList.add('active');
440
- }
441
-
442
- // ── Toast ──
443
- function showToast(msg) {
444
- const t = document.getElementById('toast');
445
- t.textContent = msg;
446
- t.classList.add('show');
447
- setTimeout(() => t.classList.remove('show'), 2500);
448
- }
449
-
450
- // ── Init ──
451
- async function init() {
452
- state = await fetchStatus();
453
- renderChannels();
454
- renderSchedule();
455
- renderStats();
456
- }
457
-
458
- init();
459
- setInterval(async () => {
460
- state = await fetchStatus();
461
- renderSchedule();
462
- renderStats();
463
- }, 30000); // refresh every 30s
464
- </script>
465
- </body>
466
- </html>
 
1
+ <!DOCTYPE html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="UTF-8"/>
5
+ <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"/>
6
+ <title>CrazyLearners Bot Dashboard</title>
7
+ <script src="https://telegram.org/js/telegram-web-app.js"></script>
8
+ <style>
9
+ :root {
10
+ --bg: #0f0f1a;
11
+ --card: #1a1a2e;
12
+ --border: #2a2a4a;
13
+ --accent: #7c3aed;
14
+ --accent2: #06b6d4;
15
+ --green: #22c55e;
16
+ --red: #ef4444;
17
+ --yellow: #f59e0b;
18
+ --text: #e2e8f0;
19
+ --muted: #64748b;
20
+ --radius: 12px;
21
+ }
22
+ * { box-sizing: border-box; margin: 0; padding: 0; }
23
+ body {
24
+ background: var(--bg);
25
+ color: var(--text);
26
+ font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
27
+ min-height: 100vh;
28
+ padding-bottom: 30px;
29
+ }
30
+
31
+ /* ── Header ── */
32
+ .header {
33
+ background: linear-gradient(135deg, #1e1b4b 0%, #312e81 50%, #1e3a5f 100%);
34
+ padding: 20px 16px 16px;
35
+ text-align: center;
36
+ border-bottom: 1px solid var(--border);
37
+ }
38
+ .header h1 { font-size: 20px; font-weight: 700; letter-spacing: -0.3px; }
39
+ .header h1 span { color: var(--accent2); }
40
+ .header p { font-size: 12px; color: var(--muted); margin-top: 4px; }
41
+ .status-dot {
42
+ display: inline-block; width: 8px; height: 8px;
43
+ background: var(--green); border-radius: 50%;
44
+ margin-right: 5px; animation: pulse 2s infinite;
45
+ }
46
+ @keyframes pulse {
47
+ 0%, 100% { opacity: 1; } 50% { opacity: 0.4; }
48
+ }
49
+
50
+ /* ── Tabs ── */
51
+ .tabs {
52
+ display: flex; background: var(--card);
53
+ border-bottom: 1px solid var(--border);
54
+ overflow-x: auto; scrollbar-width: none;
55
+ }
56
+ .tabs::-webkit-scrollbar { display: none; }
57
+ .tab {
58
+ flex: 1; min-width: 80px; padding: 12px 8px; text-align: center;
59
+ font-size: 12px; font-weight: 600; color: var(--muted);
60
+ cursor: pointer; border-bottom: 2px solid transparent;
61
+ transition: all 0.2s; white-space: nowrap;
62
+ }
63
+ .tab.active { color: var(--accent2); border-bottom-color: var(--accent2); }
64
+
65
+ /* ── Sections ── */
66
+ .section { display: none; padding: 16px; }
67
+ .section.active { display: block; }
68
+
69
+ /* ── Cards ── */
70
+ .card {
71
+ background: var(--card); border-radius: var(--radius);
72
+ border: 1px solid var(--border); margin-bottom: 12px; overflow: hidden;
73
+ }
74
+ .card-header {
75
+ display: flex; align-items: center; justify-content: space-between;
76
+ padding: 14px 16px; border-bottom: 1px solid var(--border);
77
+ cursor: pointer;
78
+ }
79
+ .card-header .title { font-weight: 700; font-size: 14px; }
80
+ .card-header .subtitle { font-size: 11px; color: var(--muted); margin-top: 2px; }
81
+ .card-header .badge {
82
+ font-size: 10px; padding: 3px 8px; border-radius: 20px;
83
+ font-weight: 600;
84
+ }
85
+ .badge-active { background: #14532d; color: var(--green); }
86
+ .badge-paused { background: #7c2020; color: var(--red); }
87
+
88
+ /* ── Content Type Rows ── */
89
+ .ct-list { padding: 4px 0; }
90
+ .ct-row {
91
+ display: flex; align-items: center; justify-content: space-between;
92
+ padding: 10px 16px; border-bottom: 1px solid var(--border);
93
+ transition: background 0.15s;
94
+ }
95
+ .ct-row:last-child { border-bottom: none; }
96
+ .ct-row:active { background: rgba(124,58,237,0.08); }
97
+ .ct-info { flex: 1; }
98
+ .ct-name { font-size: 13px; font-weight: 500; }
99
+ .ct-time { font-size: 11px; color: var(--muted); margin-top: 2px; }
100
+
101
+ /* ── Toggle Switch ── */
102
+ .toggle {
103
+ position: relative; width: 44px; height: 24px; flex-shrink: 0;
104
+ }
105
+ .toggle input { opacity: 0; width: 0; height: 0; }
106
+ .toggle-track {
107
+ position: absolute; top: 0; left: 0; right: 0; bottom: 0;
108
+ background: #374151; border-radius: 12px; cursor: pointer;
109
+ transition: background 0.25s;
110
+ }
111
+ .toggle-track::before {
112
+ content: ""; position: absolute;
113
+ width: 18px; height: 18px; border-radius: 50%;
114
+ background: white; top: 3px; left: 3px;
115
+ transition: transform 0.25s;
116
+ box-shadow: 0 1px 3px rgba(0,0,0,0.4);
117
+ }
118
+ .toggle input:checked + .toggle-track { background: var(--accent); }
119
+ .toggle input:checked + .toggle-track::before { transform: translateX(20px); }
120
+ .toggle.loading .toggle-track { opacity: 0.5; pointer-events: none; }
121
+
122
+ /* ── Stats Grid ── */
123
+ .stats-grid {
124
+ display: grid; grid-template-columns: repeat(2, 1fr); gap: 10px; margin-bottom: 14px;
125
+ }
126
+ .stat-card {
127
+ background: var(--card); border: 1px solid var(--border);
128
+ border-radius: var(--radius); padding: 14px; text-align: center;
129
+ }
130
+ .stat-value { font-size: 28px; font-weight: 800; }
131
+ .stat-label { font-size: 11px; color: var(--muted); margin-top: 4px; }
132
+ .stat-card.accent { border-color: var(--accent); }
133
+ .stat-card.accent2 { border-color: var(--accent2); }
134
+ .stat-card.green { border-color: var(--green); }
135
+ .stat-card.yellow { border-color: var(--yellow); }
136
+
137
+ /* ── Schedule Table ── */
138
+ .sched-row {
139
+ display: flex; align-items: center; padding: 10px 16px;
140
+ border-bottom: 1px solid var(--border);
141
+ }
142
+ .sched-row:last-child { border-bottom: none; }
143
+ .sched-time {
144
+ font-size: 13px; font-weight: 700; color: var(--accent2);
145
+ width: 52px; flex-shrink: 0;
146
+ }
147
+ .sched-label { font-size: 13px; flex: 1; }
148
+ .sched-channels { font-size: 10px; color: var(--muted); }
149
+
150
+ /* ── Loading / Error ── */
151
+ .loading-text { text-align: center; color: var(--muted); padding: 40px; font-size: 14px; }
152
+ .spinner {
153
+ width: 24px; height: 24px; border: 3px solid var(--border);
154
+ border-top-color: var(--accent2); border-radius: 50%;
155
+ animation: spin 0.8s linear infinite; margin: 0 auto 12px;
156
+ }
157
+ @keyframes spin { to { transform: rotate(360deg); } }
158
+
159
+ /* ── Toast ── */
160
+ .toast {
161
+ position: fixed; bottom: 20px; left: 50%; transform: translateX(-50%);
162
+ background: #1e293b; border: 1px solid var(--border);
163
+ color: var(--text); padding: 10px 18px; border-radius: 8px;
164
+ font-size: 13px; opacity: 0; transition: opacity 0.3s;
165
+ pointer-events: none; z-index: 999; white-space: nowrap;
166
+ }
167
+ .toast.show { opacity: 1; }
168
+
169
+ /* ── Expand arrow ── */
170
+ .arrow { transition: transform 0.2s; font-size: 12px; color: var(--muted); }
171
+ .arrow.open { transform: rotate(180deg); }
172
+ </style>
173
+ </head>
174
+ <body>
175
+
176
+ <div class="header">
177
+ <h1>πŸŽ“ <span>CrazyLearners</span> Bot</h1>
178
+ <p><span class="status-dot"></span>Live Dashboard</p>
179
+ </div>
180
+
181
+ <div class="tabs">
182
+ <div class="tab active" onclick="switchTab('channels')">πŸ“‘ Channels</div>
183
+ <div class="tab" onclick="switchTab('schedule')">πŸ• Schedule</div>
184
+ <div class="tab" onclick="switchTab('stats')">πŸ“Š Stats</div>
185
+ </div>
186
+
187
+ <!-- CHANNELS TAB -->
188
+ <div id="tab-channels" class="section active">
189
+ <div id="channels-content" class="loading-text">
190
+ <div class="spinner"></div>Loading channels...
191
+ </div>
192
+ </div>
193
+
194
+ <!-- SCHEDULE TAB -->
195
+ <div id="tab-schedule" class="section">
196
+ <div id="schedule-content" class="loading-text">
197
+ <div class="spinner"></div>Loading schedule...
198
+ </div>
199
+ </div>
200
+
201
+ <!-- STATS TAB -->
202
+ <div id="tab-stats" class="section">
203
+ <div id="stats-content" class="loading-text">
204
+ <div class="spinner"></div>Loading stats...
205
+ </div>
206
+ </div>
207
+
208
+ <div class="toast" id="toast"></div>
209
+
210
+ <script>
211
+ // ── API base (bot runs on HF Space) ──
212
+ const API_BASE = 'https://h3y-sam-telegram-bot.hf.space';
213
+
214
+ // ── Telegram Mini App init ──
215
+ const tg = window.Telegram?.WebApp;
216
+ if (tg) { tg.ready(); tg.expand(); }
217
+
218
+ // ── Content type metadata ──
219
+ const CT_LABELS = {
220
+ pyq_question: "πŸ“… PYQ Question",
221
+ formula_sheet: "πŸ“ Formula Sheet",
222
+ short_notes: "πŸ“ Short Notes",
223
+ mnemonic: "🧠 Memory Tricks",
224
+ concept_recap: "πŸŒ… Concept Recap",
225
+ mock_question: "🎯 Daily Mock",
226
+ motivational: "πŸŒ™ Night Motivation",
227
+ mcq_session: "πŸ§ͺ MCQ Poll Session",
228
+ };
229
+
230
+ const CT_TIMES = {
231
+ pyq_question: "7:00 AM",
232
+ formula_sheet: "9:00 AM",
233
+ short_notes: "12:00 PM",
234
+ mnemonic: "3:00 PM",
235
+ concept_recap: "6:00 PM",
236
+ mock_question: "8:00 PM",
237
+ motivational: "10:00 PM",
238
+ mcq_session: "8:00 PM",
239
+ };
240
+
241
+ let state = null;
242
+ let openChannels = {};
243
+
244
+ // ── Fetch data from API ──
245
+ async function fetchStatus() {
246
+ try {
247
+ const r = await fetch(`${API_BASE}/api/status`);
248
+ if (!r.ok) throw new Error('API error');
249
+ return await r.json();
250
+ } catch (e) {
251
+ return null;
252
+ }
253
+ }
254
+
255
+ async function toggleContentType(chKey, ct, el) {
256
+ el.classList.add('loading');
257
+ try {
258
+ const r = await fetch(`${API_BASE}/api/toggle/${chKey}/${ct}`, { method: 'POST' });
259
+ const d = await r.json();
260
+ const enabled = d.enabled;
261
+ el.querySelector('input').checked = enabled;
262
+ showToast(enabled ? `βœ… ${CT_LABELS[ct] || ct} enabled` : `⏸️ ${CT_LABELS[ct] || ct} paused`);
263
+ // Update state
264
+ if (state?.channels?.[chKey]) {
265
+ if (!state.channels[chKey].disabled_content_types) state.channels[chKey].disabled_content_types = [];
266
+ if (enabled) {
267
+ state.channels[chKey].disabled_content_types = state.channels[chKey].disabled_content_types.filter(x => x !== ct);
268
+ } else {
269
+ if (!state.channels[chKey].disabled_content_types.includes(ct))
270
+ state.channels[chKey].disabled_content_types.push(ct);
271
+ }
272
+ }
273
+ } catch(e) {
274
+ showToast('❌ Failed β€” check bot logs');
275
+ }
276
+ el.classList.remove('loading');
277
+ }
278
+
279
+ async function toggleChannel(chKey, btn) {
280
+ btn.disabled = true;
281
+ try {
282
+ const r = await fetch(`${API_BASE}/api/toggle-channel/${chKey}`, { method: 'POST' });
283
+ const d = await r.json();
284
+ showToast(d.active ? `βœ… ${d.label} resumed` : `⏸️ ${d.label} paused`);
285
+ renderChannels(); // re-render
286
+ } catch(e) {
287
+ showToast('❌ Failed');
288
+ }
289
+ btn.disabled = false;
290
+ }
291
+
292
+ // ── Render: Channels ──
293
+ function renderChannels() {
294
+ const el = document.getElementById('channels-content');
295
+ if (!state) { el.innerHTML = '<p class="loading-text">⚠️ Could not load data. Is the bot running?</p>'; return; }
296
+
297
+ const channels = state.channels || {};
298
+ let html = '';
299
+ for (const [key, cfg] of Object.entries(channels)) {
300
+ const active = cfg.active !== false;
301
+ const disabled = cfg.disabled_content_types || [];
302
+ const mcqOnly = disabled.length >= 6;
303
+ const open = openChannels[key] || false;
304
+
305
+ html += `
306
+ <div class="card">
307
+ <div class="card-header" onclick="toggleOpen('${key}')">
308
+ <div>
309
+ <div class="title">${cfg.label || key}</div>
310
+ <div class="subtitle">${cfg.id || ''} Β· ${mcqOnly ? 'MCQ Only' : 'Full Content'}</div>
311
+ </div>
312
+ <div style="display:flex;align-items:center;gap:8px">
313
+ <span class="badge ${active ? 'badge-active' : 'badge-paused'}">${active ? 'Active' : 'Paused'}</span>
314
+ <span class="arrow ${open ? 'open' : ''}" id="arrow-${key}">β–Ό</span>
315
+ </div>
316
+ </div>
317
+ ${open ? `
318
+ <div class="ct-list">
319
+ ${Object.entries(CT_LABELS).map(([ct, label]) => {
320
+ const enabled = !disabled.includes(ct);
321
+ return `
322
+ <div class="ct-row">
323
+ <div class="ct-info">
324
+ <div class="ct-name">${label}</div>
325
+ <div class="ct-time">${CT_TIMES[ct] || 'β€”'} IST</div>
326
+ </div>
327
+ <label class="toggle" id="toggle-${key}-${ct}">
328
+ <input type="checkbox" ${enabled ? 'checked' : ''}
329
+ onchange="toggleContentType('${key}','${ct}',document.getElementById('toggle-${key}-${ct}'))">
330
+ <div class="toggle-track"></div>
331
+ </label>
332
+ </div>`;
333
+ }).join('')}
334
+ <div style="padding:12px 16px">
335
+ <button onclick="toggleChannel('${key}',this)"
336
+ style="width:100%;padding:10px;border-radius:8px;border:1px solid var(--border);
337
+ background:${active ? '#7c2020' : '#14532d'};color:white;font-weight:600;
338
+ cursor:pointer;font-size:13px">
339
+ ${active ? '⏸️ Pause All Posts' : '▢️ Resume All Posts'}
340
+ </button>
341
+ </div>
342
+ </div>` : ''}
343
+ </div>`;
344
+ }
345
+ el.innerHTML = html;
346
+ }
347
+
348
+ function toggleOpen(key) {
349
+ openChannels[key] = !openChannels[key];
350
+ renderChannels();
351
+ }
352
+
353
+ // ── Render: Schedule ──
354
+ function renderSchedule() {
355
+ const el = document.getElementById('schedule-content');
356
+ if (!state) { el.innerHTML = '<p class="loading-text">⚠️ No data.</p>'; return; }
357
+
358
+ const schedule = state.schedule || {};
359
+ const channels = state.channels || {};
360
+ const rows = Object.entries(schedule)
361
+ .sort((a,b) => (a[1].hour*60+a[1].minute) - (b[1].hour*60+b[1].minute));
362
+
363
+ let html = '<div class="card"><div style="padding:4px 0">';
364
+ for (const [ct, timing] of rows) {
365
+ const h = String(timing.hour).padStart(2,'0');
366
+ const m = String(timing.minute).padStart(2,'0');
367
+ const activeChans = Object.entries(channels)
368
+ .filter(([,c]) => c.active && !(c.disabled_content_types||[]).includes(ct))
369
+ .map(([,c]) => c.label?.split(' ')[0]).join(', ');
370
+ html += `
371
+ <div class="sched-row">
372
+ <div class="sched-time">${h}:${m}</div>
373
+ <div>
374
+ <div class="sched-label">${CT_LABELS[ct] || ct}</div>
375
+ <div class="sched-channels">${activeChans || 'β€”'}</div>
376
+ </div>
377
+ </div>`;
378
+ }
379
+ html += '</div></div>';
380
+ el.innerHTML = html;
381
+ }
382
+
383
+ // ── Render: Stats ──
384
+ function renderStats() {
385
+ const el = document.getElementById('stats-content');
386
+ if (!state) { el.innerHTML = '<p class="loading-text">⚠️ No data.</p>'; return; }
387
+
388
+ const channels = state.channels || {};
389
+ const total = Object.keys(channels).length;
390
+ const active = Object.values(channels).filter(c => c.active).length;
391
+ const jobs = state.total_jobs || 0;
392
+ const users = state.user_count || 0;
393
+
394
+ el.innerHTML = `
395
+ <div class="stats-grid">
396
+ <div class="stat-card accent">
397
+ <div class="stat-value">${active}/${total}</div>
398
+ <div class="stat-label">Active Channels</div>
399
+ </div>
400
+ <div class="stat-card accent2">
401
+ <div class="stat-value">${jobs}</div>
402
+ <div class="stat-label">Scheduled Jobs</div>
403
+ </div>
404
+ <div class="stat-card green">
405
+ <div class="stat-value">${users}</div>
406
+ <div class="stat-label">DM Users</div>
407
+ </div>
408
+ <div class="stat-card yellow">
409
+ <div class="stat-value">${Object.keys(state.schedule||{}).length}</div>
410
+ <div class="stat-label">Content Types</div>
411
+ </div>
412
+ </div>
413
+ <div class="card">
414
+ <div style="padding:14px 16px;border-bottom:1px solid var(--border);font-weight:700;font-size:13px">
415
+ πŸ“‘ Channel Overview
416
+ </div>
417
+ ${Object.entries(channels).map(([key, cfg]) => {
418
+ const disabled = cfg.disabled_content_types || [];
419
+ const enabled = Object.keys(CT_LABELS).filter(ct => !disabled.includes(ct));
420
+ return `
421
+ <div class="sched-row">
422
+ <div style="flex:1">
423
+ <div class="sched-label">${cfg.label || key}</div>
424
+ <div class="sched-channels">${enabled.length} active types Β· ${cfg.id}</div>
425
+ </div>
426
+ <span class="badge ${cfg.active ? 'badge-active':'badge-paused'}">${cfg.active ? 'On':'Off'}</span>
427
+ </div>`;
428
+ }).join('')}
429
+ </div>`;
430
+ }
431
+
432
+ // ── Tab switch ──
433
+ function switchTab(name) {
434
+ document.querySelectorAll('.tab').forEach((t,i) => {
435
+ const names = ['channels','schedule','stats'];
436
+ t.classList.toggle('active', names[i] === name);
437
+ });
438
+ document.querySelectorAll('.section').forEach(s => s.classList.remove('active'));
439
+ document.getElementById(`tab-${name}`).classList.add('active');
440
+ }
441
+
442
+ // ── Toast ──
443
+ function showToast(msg) {
444
+ const t = document.getElementById('toast');
445
+ t.textContent = msg;
446
+ t.classList.add('show');
447
+ setTimeout(() => t.classList.remove('show'), 2500);
448
+ }
449
+
450
+ // ── Init ──
451
+ async function init() {
452
+ state = await fetchStatus();
453
+ renderChannels();
454
+ renderSchedule();
455
+ renderStats();
456
+ }
457
+
458
+ init();
459
+ setInterval(async () => {
460
+ state = await fetchStatus();
461
+ renderSchedule();
462
+ renderStats();
463
+ }, 30000); // refresh every 30s
464
+ </script>
465
+ </body>
466
+ </html>