File size: 13,049 Bytes
fa22010
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
add04fc
 
 
 
 
fa22010
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
---

title: Telegram Bot
emoji: πŸ€–
colorFrom: indigo
colorTo: blue
sdk: docker
app_port: 7860
---


# πŸŽ“ JEE & NEET Daily Study Bot β€” CrazyLearners Edition

> **Fully automated, multi-channel Telegram content bot** powered by **Gemini AI (Gemini 2.0 Flash)**.  
> Posts 7 unique study posts/day across multiple channels β€” with repeat prevention, interactive MCQ poll sessions, weekly branded PDF digests, and a web dashboard.

πŸ”— **Join us:** [t.me/xcrazylearners](https://t.me/xcrazylearners)

---

## ✨ Feature Overview

| Feature | Details |
|---------|---------|
| πŸ€– **Gemini AI (Gemini 2.0 Flash)** | Fast, free-tier-friendly AI with zero content filtering for academic topics |
| πŸ“‘ **Multi-channel** | Unlimited channels β€” JEE Main, NEET, JEE Advanced, or custom combos |
| πŸ—“οΈ **7 posts/day** | PYQ, Formula Sheet, Short Notes, Mnemonic, Concept Recap, Mock Question, Motivation |
| πŸ§ͺ **MCQ Poll Sessions** | 10 interactive quiz polls per session with configurable delays |
| πŸ“„ **Weekly PDF Digest** | Branded CrazyLearners PDF every Sunday β€” Short Notes + Formula Sheets compiled |
| 🚫 **Repeat Prevention** | Remembers last 60 topics per channel; always picks a fresh chapter |
| πŸ“Š **Coverage Stats** | See what % of syllabus each channel has covered |
| ⏸️ **Per-channel Control** | Pause/resume individual channels or specific content types |
| 🌐 **Web Dashboard** | Full visual admin UI hosted on Hugging Face Spaces |
| πŸ’¬ **Doubt Solver** | Students can DM the bot or @mention it in groups to get AI answers |
| πŸ“’ **Broadcast** | Admin can push messages to all registered users with rate limiting |
| πŸ”„ **Remote Sync** | History synced to a GitHub Gist for persistence across restarts |

---

## πŸ“¦ Daily Schedule (per channel, IST)

| Time | Content Type | Description |
|------|-------------|-------------|
| 7:00 AM | πŸ“… PYQ Question | Previous year MCQ with spoiler answer + explanation |
| 9:00 AM | πŸ“ Formula Sheet | 8–12 key formulas with shortcuts and derivation hints |
| 12:00 PM | πŸ“ Short Notes | 3-minute rapid revision notes |
| 3:00 PM | 🧠 Mnemonic | Memory tricks and visualizations |
| 6:00 PM | πŸŒ… Concept Recap | Evening summary + exam weightage tips |
| 8:00 PM | 🎯 Mock Question | 3 practice MCQs with step-by-step solutions |
| 10:00 PM | πŸŒ™ Motivation | Night motivation + next day's plan |
| 8:00 PM (MCQ channels) | πŸ§ͺ MCQ Poll Session | 10 live quiz polls with configurable delay between each |
| Every Sunday 9:00 PM | πŸ“„ Weekly PDF | Branded PDF of the week's Short Notes + Formula Sheets |

Each channel gets **different content** tailored to its exam focus and subject rotation.

---

## βš™οΈ Setup Guide

### Step 1 β€” Create your Telegram Bot
1. Message **@BotFather** β†’ `/newbot`
2. Copy the **API token**

### Step 2 β€” Get Gemini API Key
1. Go to [aistudio.google.com/app/apikey](https://aistudio.google.com/app/apikey)
2. Sign up β†’ **API Keys** β†’ **Create API Key**
3. Free tier is sufficient (model: `gemini-2.0-flash`)

### Step 3 β€” Create Channels & Add Bot as Admin
For each channel:
1. Create the channel in Telegram
2. **Channel Settings β†’ Administrators β†’ Add Admin**
3. Search your bot β†’ grant **Post Messages** permission

### Step 4 β€” Get Your Admin User ID
Message **@userinfobot** β†’ copy your numeric ID

### Step 5 β€” Configure Environment Variables

Create a `.env` file (or set in your hosting environment):

```env

BOT_TOKEN=7123456789:AAF...          # From @BotFather

GEMINI_API_KEY=AIza...                 # From aistudio.google.com/app/apikey

ADMIN_USER_IDS=987654321             # Comma-separated for multiple admins

GIST_ID=abc123...                    # Optional: GitHub Gist ID for remote history sync

GIST_TOKEN=ghp_...                   # Optional: GitHub Personal Access Token

```

### Step 6 β€” Configure Channels (first run)

Edit the `DEFAULT_CHANNELS` block in `content/config_manager.py`, or use the **Web Dashboard** after startup:

```python

"jee_main": {

    "id":         "@YourJEEMainChannel",

    "label":      "JEE Main Daily",

    "exam_focus": ["JEE Main"],

    "subjects":   ["physics", "chemistry", "maths"],

    "active":     True,

    "mcq_poll_enabled": False,

    "footer":     "🎯 Crack JEE Main 2025!\nπŸ“’ Share with your batch!",

    "hashtags":   { "pyq": "#JEEMain #PYQ", "formula": "#Formula", ... },

},

```

> πŸ’‘ After the first run, all config changes are saved to `data/bot_config.json` and can be edited via the Web Dashboard without touching code.



### Step 7 β€” Run



```bash

pip install -r requirements.txt

python bot.py

```



---



## πŸ› οΈ Admin Commands (DM your bot)



| Command | What it does |

|---------|-------------|

| `/start` | Admin panel β€” active channels, job count, dashboard link |

| `/help` | Full admin guide |

| `/status` | All scheduled jobs grouped by channel with next run time |

| `/channels` | List channels; tap to pause/resume any channel |

| `/preview` | Interactive: pick channel β†’ pick content type β†’ see AI preview β†’ post now |

| `/preview <channel_key> <type>` | Direct preview, e.g. `/preview jee_main formula_sheet` |

| `/coverage` | Chapter coverage % per channel β€” see how much syllabus has been covered |

| `/stats` | Rich analytics dashboard with progress bars per subject |

| `/mcq_session <channel_key>` | Manually trigger a 10-poll MCQ session |
| `/force_digest <channel_key>` | Immediately generate and send the weekly PDF |
| `/broadcast <message>` | Push a message to all registered users |
| `/set_time <type> <HH:MM>` | Change posting time, e.g. `/set_time short_notes 11:30` |
| `/add_channel <key> <id> <label>` | Register a new channel |
| `/del_channel <key>` | Remove a channel |
| `/healthcheck` | Test all subsystems: Gemini API, Scheduler, Gist, User DB, Error Log |

---

## πŸ§ͺ MCQ Poll Session

Each session posts **10 quiz polls** to a channel with configurable delays:

- **Automatic:** Runs daily at 8:00 PM IST for MCQ-enabled channels
- **Manual:** `/mcq_session <channel_key>` or via the inline menu
- **Delay:** Configurable per channel (`mcq_poll_delay_min` / `mcq_poll_delay_max` in seconds)
- Each poll is a native Telegram Quiz Poll with the correct answer and explanation

```python

# In config, per channel:

"mcq_poll_enabled": True,

"mcq_poll_delay_min": 60,    # seconds between polls

"mcq_poll_delay_max": 90,

```

---

## πŸ“„ Weekly PDF Digest (CrazyLearners Branding)

Every **Sunday at 9:00 PM IST**, the bot:
1. Compiles all **Short Notes** and **Formula Sheets** posted that week
2. Generates a branded PDF with:
   - Cover page (CrazyLearners purple/teal design)
   - Auto-generated Table of Contents
   - Subject pill badges + Chapter cards
   - Justified body text with sub-heading detection
   - Page header/footer with brand name + `t.me/xcrazylearners`
   - Back page with CTA (join our community)
3. Sends the PDF to each active channel with a branded caption

**Force a digest anytime:** `/force_digest <channel_key>`

---

## 🚫 Repeat Prevention

The bot tracks the last **60 topics** per *(channel Γ— content type Γ— subject)* in `data/content_history.json`.

- Excludes all recently used chapters when picking a new topic
- If all chapters are used, picks from the **oldest half** (least recently used)
- Each channel maintains **independent history**

**Reset history:** `/coverage` β†’ tap "Reset a channel's history"

**Remote sync:** If `GIST_ID` and `GIST_TOKEN` are configured, history is synced to a private GitHub Gist so it survives container restarts on Hugging Face Spaces.

---

## βž• Adding a New Channel

1. Create the Telegram channel
2. Add your bot as Admin with Post Messages permission
3. Use the bot command: `/add_channel <key> <@channel_username or -100 ID> <Label>`  
   Example (Public): `/add_channel neet_2 @NEET_MyChannel "NEET Daily 2"`
   Example (Private): `/add_channel mock_priv -1001234567890 "Private 1"`
   
   *Tip: When you add the bot as an admin to a private channel, it will automatically DM you its numeric ID.*
4. Or add via the **Web Dashboard β†’ Channel Manager**

The new channel is automatically scheduled β€” no restart needed.

---

## 🌐 Web Dashboard

The bot exposes a Flask/Gradio web dashboard for visual management:

- **Add/Delete/Toggle Channels**
- **Set posting schedules** (CRON-style)
- **Manage syllabus** (add subjects, chapters)
- **Trigger content** to any channel instantly
- **Edit AI prompts** for each content type

Dashboard URL: configured in `DEFAULT_SETTINGS["dashboard_url"]`

---

## πŸš€ Deployment

### Hugging Face Spaces (Current)
The bot runs as a Docker Space. Set all env vars in **Settings β†’ Variables and secrets**.

### Railway / Render
1. Push this folder to a GitHub repo
2. Connect to Railway or Render
3. Set env vars: `BOT_TOKEN`, `GEMINI_API_KEY`, `ADMIN_USER_IDS`
4. Deploy as a **Background Worker** (no open port needed)

### VPS / Self-hosted
```bash

screen -S jeebot

python bot.py

# Ctrl+A D to detach

```

---

## πŸ“ Project Structure

```

JEE, NEET & Advance Content Manager/

β”œβ”€β”€ bot.py                      ← Entry point; starts polling + dashboard server

β”œβ”€β”€ config.py                   ← Env vars + Gemini settings (model, tokens, temp)

β”œβ”€β”€ requirements.txt

β”œβ”€β”€ data/

β”‚   β”œβ”€β”€ bot_config.json         ← Auto-saved dynamic config (channels, schedule)

β”‚   β”œβ”€β”€ content_history.json    ← Repeat-prevention tracker

β”‚   β”œβ”€β”€ syllabus.json           ← Full JEE/NEET syllabus (chapters per subject)

β”‚   β”œβ”€β”€ prompts.json            ← Custom AI prompt templates (editable via dashboard)

β”‚   └── digests/                ← Generated weekly PDF files

β”œβ”€β”€ content/

β”‚   β”œβ”€β”€ generator.py            ← Gemini AI content generation + Markdown sanitizer

β”‚   β”œβ”€β”€ history.py              ← Chapter tracker + weekly archive for PDFs

β”‚   β”œβ”€β”€ pdf_generator.py        ← Branded CrazyLearners PDF builder (fpdf2)

β”‚   β”œβ”€β”€ config_manager.py       ← Dynamic channel/schedule config (JSON-backed)

β”‚   β”œβ”€β”€ syllabus_manager.py     ← Syllabus loader with recursive chapter extraction

β”‚   β”œβ”€β”€ template_manager.py     ← AI prompt template manager

β”‚   β”œβ”€β”€ doubt_solver.py         ← Gemini-powered doubt answering for students

β”‚   β”œβ”€β”€ remote_storage.py       ← GitHub Gist sync for history persistence

β”‚   └── user_registry.py        ← Registered user DB (for broadcast)

β”œβ”€β”€ scheduler/

β”‚   └── job_scheduler.py        ← APScheduler: 1 job per (content_type Γ— channel)

β”‚                                  _safe_send_message with Markdown parse recovery

└── handlers/

    β”œβ”€β”€ commands.py             ← /start /status /channels /preview /mcq_session etc.

    β”œβ”€β”€ callbacks.py            ← Inline button actions (pause, preview, post-now)

    β”œβ”€β”€ doubt_handler.py        ← DM + group @mention doubt handler

    └── menu_router.py          ← Routes reply-keyboard button taps

```

---

## πŸ”§ Key Configuration Constants (`config.py`)

| Constant | Default | Purpose |
|----------|---------|---------|
| `GEMINI_MODEL` | `gemini-2.0-flash` | Gemini model for all AI generation |
| `GEMINI_MAX_TOKENS` | `3500` | Max tokens per AI response (high enough for 10-MCQ JSON) |
| `GEMINI_TEMPERATURE` | `0.7` | Creativity vs consistency balance |
| `HISTORY_DEPTH` | `60` | How many past topics to remember before reuse is allowed |

---

## πŸ› Known Issues Fixed (v2.0)

| Bug | Fix |
|-----|-----|
| `Can't parse entities` β€” Telegram Markdown errors | `_clean_markdown()` now strips code blocks before counting `*`/`_` markers; `_safe_send_message()` auto-retries as plain text on parse failure |
| `Message is too long` | Hard 4000-char truncation in `_clean_markdown()` + `_safe_send_message()` |
| `Could not generate enough MCQs` | `GEMINI_MAX_TOKENS` raised to 3500; `_parse_mcq_json()` uses `find('[')` + `rfind(']')` instead of greedy regex; auto-retries once before giving up |
| MCQ callback blocking event loop 15 min | `asyncio.create_task()` instead of `await` in callback handler |
| PDF file handle leak | Wrapped `send_document` in `with open(...) as f` |
| `KeyError` on custom content type in `/set_time` | Changed `CONTENT_LABELS[ctype]` β†’ `.get(ctype, ctype)` |
| Broadcast hitting Telegram 429 rate limit | `asyncio.sleep(0.05)` between each send |
| `get_me()` API call on every group message | Cached in `context.bot_data` after first call |
| Archive storing empty date | Uses `datetime.now()` instead of missing env var |
| Preview command crashing on dict response | Handles quiz/text/error dict shapes correctly |