Spaces:
Running
Running
Upload 49 files
Browse files- Dockerfile +24 -24
- README.md +292 -292
- bot.py +3 -3
- config.py +5 -5
- content/doubt_solver.py +123 -119
- content/generator.py +521 -516
- handlers/commands.py +12 -12
- refactor.py +69 -0
- requirements.txt +1 -1
- verify_gemini.py +30 -0
- web_app/dashboard.html +1 -1
Dockerfile
CHANGED
|
@@ -1,24 +1,24 @@
|
|
| 1 |
-
# Use an official Python runtime as a parent image
|
| 2 |
-
FROM python:3.11-slim
|
| 3 |
-
|
| 4 |
-
# Set the working directory in the container
|
| 5 |
-
WORKDIR /app
|
| 6 |
-
|
| 7 |
-
# Copy the current directory contents into the container at /app
|
| 8 |
-
COPY . /app
|
| 9 |
-
|
| 10 |
-
# Install any needed packages specified in requirements.txt
|
| 11 |
-
RUN pip install --no-cache-dir -r requirements.txt
|
| 12 |
-
|
| 13 |
-
# Create the data directory
|
| 14 |
-
RUN mkdir -p data
|
| 15 |
-
|
| 16 |
-
# Define environment variables (These will be overwritten by Hugging Face Secrets)
|
| 17 |
-
ENV BOT_TOKEN=""
|
| 18 |
-
ENV
|
| 19 |
-
ENV ADMIN_USER_IDS=""
|
| 20 |
-
ENV GIST_ID=""
|
| 21 |
-
ENV GIST_TOKEN=""
|
| 22 |
-
|
| 23 |
-
# Run bot.py when the container launches
|
| 24 |
-
CMD ["python", "bot.py"]
|
|
|
|
| 1 |
+
# Use an official Python runtime as a parent image
|
| 2 |
+
FROM python:3.11-slim
|
| 3 |
+
|
| 4 |
+
# Set the working directory in the container
|
| 5 |
+
WORKDIR /app
|
| 6 |
+
|
| 7 |
+
# Copy the current directory contents into the container at /app
|
| 8 |
+
COPY . /app
|
| 9 |
+
|
| 10 |
+
# Install any needed packages specified in requirements.txt
|
| 11 |
+
RUN pip install --no-cache-dir -r requirements.txt
|
| 12 |
+
|
| 13 |
+
# Create the data directory
|
| 14 |
+
RUN mkdir -p data
|
| 15 |
+
|
| 16 |
+
# Define environment variables (These will be overwritten by Hugging Face Secrets)
|
| 17 |
+
ENV BOT_TOKEN=""
|
| 18 |
+
ENV GEMINI_API_KEY=""
|
| 19 |
+
ENV ADMIN_USER_IDS=""
|
| 20 |
+
ENV GIST_ID=""
|
| 21 |
+
ENV GIST_TOKEN=""
|
| 22 |
+
|
| 23 |
+
# Run bot.py when the container launches
|
| 24 |
+
CMD ["python", "bot.py"]
|
README.md
CHANGED
|
@@ -1,292 +1,292 @@
|
|
| 1 |
-
---
|
| 2 |
-
title: Telegram Bot
|
| 3 |
-
emoji: π€
|
| 4 |
-
colorFrom: indigo
|
| 5 |
-
colorTo: blue
|
| 6 |
-
sdk: docker
|
| 7 |
-
app_port: 7860
|
| 8 |
-
---
|
| 9 |
-
|
| 10 |
-
# π JEE & NEET Daily Study Bot β CrazyLearners Edition
|
| 11 |
-
|
| 12 |
-
> **Fully automated, multi-channel Telegram content bot** powered by **
|
| 13 |
-
> Posts 7 unique study posts/day across multiple channels β with repeat prevention, interactive MCQ poll sessions, weekly branded PDF digests, and a web dashboard.
|
| 14 |
-
|
| 15 |
-
π **Join us:** [t.me/xcrazylearners](https://t.me/xcrazylearners)
|
| 16 |
-
|
| 17 |
-
---
|
| 18 |
-
|
| 19 |
-
## β¨ Feature Overview
|
| 20 |
-
|
| 21 |
-
| Feature | Details |
|
| 22 |
-
|---------|---------|
|
| 23 |
-
| π€ **
|
| 24 |
-
| π‘ **Multi-channel** | Unlimited channels β JEE Main, NEET, JEE Advanced, or custom combos |
|
| 25 |
-
| ποΈ **7 posts/day** | PYQ, Formula Sheet, Short Notes, Mnemonic, Concept Recap, Mock Question, Motivation |
|
| 26 |
-
| π§ͺ **MCQ Poll Sessions** | 10 interactive quiz polls per session with configurable delays |
|
| 27 |
-
| π **Weekly PDF Digest** | Branded CrazyLearners PDF every Sunday β Short Notes + Formula Sheets compiled |
|
| 28 |
-
| π« **Repeat Prevention** | Remembers last 60 topics per channel; always picks a fresh chapter |
|
| 29 |
-
| π **Coverage Stats** | See what % of syllabus each channel has covered |
|
| 30 |
-
| βΈοΈ **Per-channel Control** | Pause/resume individual channels or specific content types |
|
| 31 |
-
| π **Web Dashboard** | Full visual admin UI hosted on Hugging Face Spaces |
|
| 32 |
-
| π¬ **Doubt Solver** | Students can DM the bot or @mention it in groups to get AI answers |
|
| 33 |
-
| π’ **Broadcast** | Admin can push messages to all registered users with rate limiting |
|
| 34 |
-
| π **Remote Sync** | History synced to a GitHub Gist for persistence across restarts |
|
| 35 |
-
|
| 36 |
-
---
|
| 37 |
-
|
| 38 |
-
## π¦ Daily Schedule (per channel, IST)
|
| 39 |
-
|
| 40 |
-
| Time | Content Type | Description |
|
| 41 |
-
|------|-------------|-------------|
|
| 42 |
-
| 7:00 AM | π
PYQ Question | Previous year MCQ with spoiler answer + explanation |
|
| 43 |
-
| 9:00 AM | π Formula Sheet | 8β12 key formulas with shortcuts and derivation hints |
|
| 44 |
-
| 12:00 PM | π Short Notes | 3-minute rapid revision notes |
|
| 45 |
-
| 3:00 PM | π§ Mnemonic | Memory tricks and visualizations |
|
| 46 |
-
| 6:00 PM | π
Concept Recap | Evening summary + exam weightage tips |
|
| 47 |
-
| 8:00 PM | π― Mock Question | 3 practice MCQs with step-by-step solutions |
|
| 48 |
-
| 10:00 PM | π Motivation | Night motivation + next day's plan |
|
| 49 |
-
| 8:00 PM (MCQ channels) | π§ͺ MCQ Poll Session | 10 live quiz polls with configurable delay between each |
|
| 50 |
-
| Every Sunday 9:00 PM | π Weekly PDF | Branded PDF of the week's Short Notes + Formula Sheets |
|
| 51 |
-
|
| 52 |
-
Each channel gets **different content** tailored to its exam focus and subject rotation.
|
| 53 |
-
|
| 54 |
-
---
|
| 55 |
-
|
| 56 |
-
## βοΈ Setup Guide
|
| 57 |
-
|
| 58 |
-
### Step 1 β Create your Telegram Bot
|
| 59 |
-
1. Message **@BotFather** β `/newbot`
|
| 60 |
-
2. Copy the **API token**
|
| 61 |
-
|
| 62 |
-
### Step 2 β Get
|
| 63 |
-
1. Go to [
|
| 64 |
-
2. Sign up β **API Keys** β **Create API Key**
|
| 65 |
-
3. Free tier is sufficient (model: `
|
| 66 |
-
|
| 67 |
-
### Step 3 β Create Channels & Add Bot as Admin
|
| 68 |
-
For each channel:
|
| 69 |
-
1. Create the channel in Telegram
|
| 70 |
-
2. **Channel Settings β Administrators β Add Admin**
|
| 71 |
-
3. Search your bot β grant **Post Messages** permission
|
| 72 |
-
|
| 73 |
-
### Step 4 β Get Your Admin User ID
|
| 74 |
-
Message **@userinfobot** β copy your numeric ID
|
| 75 |
-
|
| 76 |
-
### Step 5 β Configure Environment Variables
|
| 77 |
-
|
| 78 |
-
Create a `.env` file (or set in your hosting environment):
|
| 79 |
-
|
| 80 |
-
```env
|
| 81 |
-
BOT_TOKEN=7123456789:AAF... # From @BotFather
|
| 82 |
-
|
| 83 |
-
ADMIN_USER_IDS=987654321 # Comma-separated for multiple admins
|
| 84 |
-
GIST_ID=abc123... # Optional: GitHub Gist ID for remote history sync
|
| 85 |
-
GIST_TOKEN=ghp_... # Optional: GitHub Personal Access Token
|
| 86 |
-
```
|
| 87 |
-
|
| 88 |
-
### Step 6 β Configure Channels (first run)
|
| 89 |
-
|
| 90 |
-
Edit the `DEFAULT_CHANNELS` block in `content/config_manager.py`, or use the **Web Dashboard** after startup:
|
| 91 |
-
|
| 92 |
-
```python
|
| 93 |
-
"jee_main": {
|
| 94 |
-
"id": "@YourJEEMainChannel",
|
| 95 |
-
"label": "JEE Main Daily",
|
| 96 |
-
"exam_focus": ["JEE Main"],
|
| 97 |
-
"subjects": ["physics", "chemistry", "maths"],
|
| 98 |
-
"active": True,
|
| 99 |
-
"mcq_poll_enabled": False,
|
| 100 |
-
"footer": "π― Crack JEE Main 2025!\nπ’ Share with your batch!",
|
| 101 |
-
"hashtags": { "pyq": "#JEEMain #PYQ", "formula": "#Formula", ... },
|
| 102 |
-
},
|
| 103 |
-
```
|
| 104 |
-
|
| 105 |
-
> π‘ 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.
|
| 106 |
-
|
| 107 |
-
### Step 7 β Run
|
| 108 |
-
|
| 109 |
-
```bash
|
| 110 |
-
pip install -r requirements.txt
|
| 111 |
-
python bot.py
|
| 112 |
-
```
|
| 113 |
-
|
| 114 |
-
---
|
| 115 |
-
|
| 116 |
-
## π οΈ Admin Commands (DM your bot)
|
| 117 |
-
|
| 118 |
-
| Command | What it does |
|
| 119 |
-
|---------|-------------|
|
| 120 |
-
| `/start` | Admin panel β active channels, job count, dashboard link |
|
| 121 |
-
| `/help` | Full admin guide |
|
| 122 |
-
| `/status` | All scheduled jobs grouped by channel with next run time |
|
| 123 |
-
| `/channels` | List channels; tap to pause/resume any channel |
|
| 124 |
-
| `/preview` | Interactive: pick channel
|
| 125 |
-
| `/preview <channel_key> <type>` | Direct preview, e.g. `/preview jee_main formula_sheet` |
|
| 126 |
-
| `/coverage` | Chapter coverage % per channel β see how much syllabus has been covered |
|
| 127 |
-
| `/stats` | Rich analytics dashboard with progress bars per subject |
|
| 128 |
-
| `/mcq_session <channel_key>` | Manually trigger a 10-poll MCQ session |
|
| 129 |
-
| `/force_digest <channel_key>` | Immediately generate and send the weekly PDF |
|
| 130 |
-
| `/broadcast <message>` | Push a message to all registered users |
|
| 131 |
-
| `/set_time <type> <HH:MM>` | Change posting time, e.g. `/set_time short_notes 11:30` |
|
| 132 |
-
| `/add_channel <key> <id> <label>` | Register a new channel |
|
| 133 |
-
| `/del_channel <key>` | Remove a channel |
|
| 134 |
-
| `/healthcheck` | Test all subsystems:
|
| 135 |
-
|
| 136 |
-
---
|
| 137 |
-
|
| 138 |
-
## π§ͺ MCQ Poll Session
|
| 139 |
-
|
| 140 |
-
Each session posts **10 quiz polls** to a channel with configurable delays:
|
| 141 |
-
|
| 142 |
-
- **Automatic:** Runs daily at 8:00 PM IST for MCQ-enabled channels
|
| 143 |
-
- **Manual:** `/mcq_session <channel_key>` or via the inline menu
|
| 144 |
-
- **Delay:** Configurable per channel (`mcq_poll_delay_min` / `mcq_poll_delay_max` in seconds)
|
| 145 |
-
- Each poll is a native Telegram Quiz Poll with the correct answer and explanation
|
| 146 |
-
|
| 147 |
-
```python
|
| 148 |
-
# In config, per channel:
|
| 149 |
-
"mcq_poll_enabled": True,
|
| 150 |
-
"mcq_poll_delay_min": 60, # seconds between polls
|
| 151 |
-
"mcq_poll_delay_max": 90,
|
| 152 |
-
```
|
| 153 |
-
|
| 154 |
-
---
|
| 155 |
-
|
| 156 |
-
## π Weekly PDF Digest (CrazyLearners Branding)
|
| 157 |
-
|
| 158 |
-
Every **Sunday at 9:00 PM IST**, the bot:
|
| 159 |
-
1. Compiles all **Short Notes** and **Formula Sheets** posted that week
|
| 160 |
-
2. Generates a branded PDF with:
|
| 161 |
-
- Cover page (CrazyLearners purple/teal design)
|
| 162 |
-
- Auto-generated Table of Contents
|
| 163 |
-
- Subject pill badges + Chapter cards
|
| 164 |
-
- Justified body text with sub-heading detection
|
| 165 |
-
- Page header/footer with brand name + `t.me/xcrazylearners`
|
| 166 |
-
- Back page with CTA (join our community)
|
| 167 |
-
3. Sends the PDF to each active channel with a branded caption
|
| 168 |
-
|
| 169 |
-
**Force a digest anytime:** `/force_digest <channel_key>`
|
| 170 |
-
|
| 171 |
-
---
|
| 172 |
-
|
| 173 |
-
## π« Repeat Prevention
|
| 174 |
-
|
| 175 |
-
The bot tracks the last **60 topics** per *(channel Γ content type Γ subject)* in `data/content_history.json`.
|
| 176 |
-
|
| 177 |
-
- Excludes all recently used chapters when picking a new topic
|
| 178 |
-
- If all chapters are used, picks from the **oldest half** (least recently used)
|
| 179 |
-
- Each channel maintains **independent history**
|
| 180 |
-
|
| 181 |
-
**Reset history:** `/coverage` β tap "Reset a channel's history"
|
| 182 |
-
|
| 183 |
-
**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.
|
| 184 |
-
|
| 185 |
-
---
|
| 186 |
-
|
| 187 |
-
## β Adding a New Channel
|
| 188 |
-
|
| 189 |
-
1. Create the Telegram channel
|
| 190 |
-
2. Add your bot as Admin with Post Messages permission
|
| 191 |
-
3. Use the bot command: `/add_channel <key> <@channel_id> <Label>`
|
| 192 |
-
Example: `/add_channel neet_2 @NEET_MyChannel "NEET Daily 2"`
|
| 193 |
-
4. Or add via the **Web Dashboard β Channel Manager**
|
| 194 |
-
|
| 195 |
-
The new channel is automatically scheduled β no restart needed.
|
| 196 |
-
|
| 197 |
-
---
|
| 198 |
-
|
| 199 |
-
## π Web Dashboard
|
| 200 |
-
|
| 201 |
-
The bot exposes a Flask/Gradio web dashboard for visual management:
|
| 202 |
-
|
| 203 |
-
- **Add/Delete/Toggle Channels**
|
| 204 |
-
- **Set posting schedules** (CRON-style)
|
| 205 |
-
- **Manage syllabus** (add subjects, chapters)
|
| 206 |
-
- **Trigger content** to any channel instantly
|
| 207 |
-
- **Edit AI prompts** for each content type
|
| 208 |
-
|
| 209 |
-
Dashboard URL: configured in `DEFAULT_SETTINGS["dashboard_url"]`
|
| 210 |
-
|
| 211 |
-
---
|
| 212 |
-
|
| 213 |
-
## π Deployment
|
| 214 |
-
|
| 215 |
-
### Hugging Face Spaces (Current)
|
| 216 |
-
The bot runs as a Docker Space. Set all env vars in **Settings β Variables and secrets**.
|
| 217 |
-
|
| 218 |
-
### Railway / Render
|
| 219 |
-
1. Push this folder to a GitHub repo
|
| 220 |
-
2. Connect to Railway or Render
|
| 221 |
-
3. Set env vars: `BOT_TOKEN`, `
|
| 222 |
-
4. Deploy as a **Background Worker** (no open port needed)
|
| 223 |
-
|
| 224 |
-
### VPS / Self-hosted
|
| 225 |
-
```bash
|
| 226 |
-
screen -S jeebot
|
| 227 |
-
python bot.py
|
| 228 |
-
# Ctrl+A D to detach
|
| 229 |
-
```
|
| 230 |
-
|
| 231 |
-
---
|
| 232 |
-
|
| 233 |
-
## π Project Structure
|
| 234 |
-
|
| 235 |
-
```
|
| 236 |
-
JEE, NEET & Advance Content Manager/
|
| 237 |
-
βββ bot.py β Entry point; starts polling + dashboard server
|
| 238 |
-
βββ config.py β Env vars +
|
| 239 |
-
βββ requirements.txt
|
| 240 |
-
βββ data/
|
| 241 |
-
β βββ bot_config.json β Auto-saved dynamic config (channels, schedule)
|
| 242 |
-
β βββ content_history.json β Repeat-prevention tracker
|
| 243 |
-
β βββ syllabus.json β Full JEE/NEET syllabus (chapters per subject)
|
| 244 |
-
β βββ prompts.json β Custom AI prompt templates (editable via dashboard)
|
| 245 |
-
β βββ digests/ β Generated weekly PDF files
|
| 246 |
-
βββ content/
|
| 247 |
-
β βββ generator.py β
|
| 248 |
-
β βββ history.py β Chapter tracker + weekly archive for PDFs
|
| 249 |
-
β βββ pdf_generator.py β Branded CrazyLearners PDF builder (fpdf2)
|
| 250 |
-
β βββ config_manager.py β Dynamic channel/schedule config (JSON-backed)
|
| 251 |
-
β βββ syllabus_manager.py β Syllabus loader with recursive chapter extraction
|
| 252 |
-
β βββ template_manager.py β AI prompt template manager
|
| 253 |
-
β βββ doubt_solver.py β
|
| 254 |
-
β βββ remote_storage.py β GitHub Gist sync for history persistence
|
| 255 |
-
β βββ user_registry.py β Registered user DB (for broadcast)
|
| 256 |
-
βββ scheduler/
|
| 257 |
-
β βββ job_scheduler.py β APScheduler: 1 job per (content_type Γ channel)
|
| 258 |
-
β _safe_send_message with Markdown parse recovery
|
| 259 |
-
βββ handlers/
|
| 260 |
-
βββ commands.py β /start /status /channels /preview /mcq_session etc.
|
| 261 |
-
βββ callbacks.py β Inline button actions (pause, preview, post-now)
|
| 262 |
-
βββ doubt_handler.py β DM + group @mention doubt handler
|
| 263 |
-
βββ menu_router.py β Routes reply-keyboard button taps
|
| 264 |
-
```
|
| 265 |
-
|
| 266 |
-
---
|
| 267 |
-
|
| 268 |
-
## π§ Key Configuration Constants (`config.py`)
|
| 269 |
-
|
| 270 |
-
| Constant | Default | Purpose |
|
| 271 |
-
|----------|---------|---------|
|
| 272 |
-
| `
|
| 273 |
-
| `
|
| 274 |
-
| `
|
| 275 |
-
| `HISTORY_DEPTH` | `60` | How many past topics to remember before reuse is allowed |
|
| 276 |
-
|
| 277 |
-
---
|
| 278 |
-
|
| 279 |
-
## π Known Issues Fixed (v2.0)
|
| 280 |
-
|
| 281 |
-
| Bug | Fix |
|
| 282 |
-
|-----|-----|
|
| 283 |
-
| `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 |
|
| 284 |
-
| `Message is too long` | Hard 4000-char truncation in `_clean_markdown()` + `_safe_send_message()` |
|
| 285 |
-
| `Could not generate enough MCQs` | `
|
| 286 |
-
| MCQ callback blocking event loop 15 min | `asyncio.create_task()` instead of `await` in callback handler |
|
| 287 |
-
| PDF file handle leak | Wrapped `send_document` in `with open(...) as f` |
|
| 288 |
-
| `KeyError` on custom content type in `/set_time` | Changed `CONTENT_LABELS[ctype]` β `.get(ctype, ctype)` |
|
| 289 |
-
| Broadcast hitting Telegram 429 rate limit | `asyncio.sleep(0.05)` between each send |
|
| 290 |
-
| `get_me()` API call on every group message | Cached in `context.bot_data` after first call |
|
| 291 |
-
| Archive storing empty date | Uses `datetime.now()` instead of missing env var |
|
| 292 |
-
| Preview command crashing on dict response | Handles quiz/text/error dict shapes correctly |
|
|
|
|
| 1 |
+
---
|
| 2 |
+
title: Telegram Bot
|
| 3 |
+
emoji: π€
|
| 4 |
+
colorFrom: indigo
|
| 5 |
+
colorTo: blue
|
| 6 |
+
sdk: docker
|
| 7 |
+
app_port: 7860
|
| 8 |
+
---
|
| 9 |
+
|
| 10 |
+
# π JEE & NEET Daily Study Bot β CrazyLearners Edition
|
| 11 |
+
|
| 12 |
+
> **Fully automated, multi-channel Telegram content bot** powered by **Gemini AI (Gemini 2.0 Flash)**.
|
| 13 |
+
> Posts 7 unique study posts/day across multiple channels β with repeat prevention, interactive MCQ poll sessions, weekly branded PDF digests, and a web dashboard.
|
| 14 |
+
|
| 15 |
+
π **Join us:** [t.me/xcrazylearners](https://t.me/xcrazylearners)
|
| 16 |
+
|
| 17 |
+
---
|
| 18 |
+
|
| 19 |
+
## β¨ Feature Overview
|
| 20 |
+
|
| 21 |
+
| Feature | Details |
|
| 22 |
+
|---------|---------|
|
| 23 |
+
| π€ **Gemini AI (Gemini 2.0 Flash)** | Fast, free-tier-friendly AI with zero content filtering for academic topics |
|
| 24 |
+
| π‘ **Multi-channel** | Unlimited channels β JEE Main, NEET, JEE Advanced, or custom combos |
|
| 25 |
+
| ποΈ **7 posts/day** | PYQ, Formula Sheet, Short Notes, Mnemonic, Concept Recap, Mock Question, Motivation |
|
| 26 |
+
| π§ͺ **MCQ Poll Sessions** | 10 interactive quiz polls per session with configurable delays |
|
| 27 |
+
| π **Weekly PDF Digest** | Branded CrazyLearners PDF every Sunday β Short Notes + Formula Sheets compiled |
|
| 28 |
+
| π« **Repeat Prevention** | Remembers last 60 topics per channel; always picks a fresh chapter |
|
| 29 |
+
| π **Coverage Stats** | See what % of syllabus each channel has covered |
|
| 30 |
+
| βΈοΈ **Per-channel Control** | Pause/resume individual channels or specific content types |
|
| 31 |
+
| π **Web Dashboard** | Full visual admin UI hosted on Hugging Face Spaces |
|
| 32 |
+
| π¬ **Doubt Solver** | Students can DM the bot or @mention it in groups to get AI answers |
|
| 33 |
+
| π’ **Broadcast** | Admin can push messages to all registered users with rate limiting |
|
| 34 |
+
| π **Remote Sync** | History synced to a GitHub Gist for persistence across restarts |
|
| 35 |
+
|
| 36 |
+
---
|
| 37 |
+
|
| 38 |
+
## π¦ Daily Schedule (per channel, IST)
|
| 39 |
+
|
| 40 |
+
| Time | Content Type | Description |
|
| 41 |
+
|------|-------------|-------------|
|
| 42 |
+
| 7:00 AM | π
PYQ Question | Previous year MCQ with spoiler answer + explanation |
|
| 43 |
+
| 9:00 AM | π Formula Sheet | 8β12 key formulas with shortcuts and derivation hints |
|
| 44 |
+
| 12:00 PM | π Short Notes | 3-minute rapid revision notes |
|
| 45 |
+
| 3:00 PM | π§ Mnemonic | Memory tricks and visualizations |
|
| 46 |
+
| 6:00 PM | π
Concept Recap | Evening summary + exam weightage tips |
|
| 47 |
+
| 8:00 PM | π― Mock Question | 3 practice MCQs with step-by-step solutions |
|
| 48 |
+
| 10:00 PM | π Motivation | Night motivation + next day's plan |
|
| 49 |
+
| 8:00 PM (MCQ channels) | π§ͺ MCQ Poll Session | 10 live quiz polls with configurable delay between each |
|
| 50 |
+
| Every Sunday 9:00 PM | π Weekly PDF | Branded PDF of the week's Short Notes + Formula Sheets |
|
| 51 |
+
|
| 52 |
+
Each channel gets **different content** tailored to its exam focus and subject rotation.
|
| 53 |
+
|
| 54 |
+
---
|
| 55 |
+
|
| 56 |
+
## βοΈ Setup Guide
|
| 57 |
+
|
| 58 |
+
### Step 1 β Create your Telegram Bot
|
| 59 |
+
1. Message **@BotFather** β `/newbot`
|
| 60 |
+
2. Copy the **API token**
|
| 61 |
+
|
| 62 |
+
### Step 2 β Get Gemini API Key
|
| 63 |
+
1. Go to [aistudio.google.com/app/apikey](https://aistudio.google.com/app/apikey)
|
| 64 |
+
2. Sign up β **API Keys** β **Create API Key**
|
| 65 |
+
3. Free tier is sufficient (model: `gemini-2.0-flash`)
|
| 66 |
+
|
| 67 |
+
### Step 3 β Create Channels & Add Bot as Admin
|
| 68 |
+
For each channel:
|
| 69 |
+
1. Create the channel in Telegram
|
| 70 |
+
2. **Channel Settings β Administrators β Add Admin**
|
| 71 |
+
3. Search your bot β grant **Post Messages** permission
|
| 72 |
+
|
| 73 |
+
### Step 4 β Get Your Admin User ID
|
| 74 |
+
Message **@userinfobot** β copy your numeric ID
|
| 75 |
+
|
| 76 |
+
### Step 5 β Configure Environment Variables
|
| 77 |
+
|
| 78 |
+
Create a `.env` file (or set in your hosting environment):
|
| 79 |
+
|
| 80 |
+
```env
|
| 81 |
+
BOT_TOKEN=7123456789:AAF... # From @BotFather
|
| 82 |
+
GEMINI_API_KEY=AIza... # From aistudio.google.com/app/apikey
|
| 83 |
+
ADMIN_USER_IDS=987654321 # Comma-separated for multiple admins
|
| 84 |
+
GIST_ID=abc123... # Optional: GitHub Gist ID for remote history sync
|
| 85 |
+
GIST_TOKEN=ghp_... # Optional: GitHub Personal Access Token
|
| 86 |
+
```
|
| 87 |
+
|
| 88 |
+
### Step 6 β Configure Channels (first run)
|
| 89 |
+
|
| 90 |
+
Edit the `DEFAULT_CHANNELS` block in `content/config_manager.py`, or use the **Web Dashboard** after startup:
|
| 91 |
+
|
| 92 |
+
```python
|
| 93 |
+
"jee_main": {
|
| 94 |
+
"id": "@YourJEEMainChannel",
|
| 95 |
+
"label": "JEE Main Daily",
|
| 96 |
+
"exam_focus": ["JEE Main"],
|
| 97 |
+
"subjects": ["physics", "chemistry", "maths"],
|
| 98 |
+
"active": True,
|
| 99 |
+
"mcq_poll_enabled": False,
|
| 100 |
+
"footer": "π― Crack JEE Main 2025!\nπ’ Share with your batch!",
|
| 101 |
+
"hashtags": { "pyq": "#JEEMain #PYQ", "formula": "#Formula", ... },
|
| 102 |
+
},
|
| 103 |
+
```
|
| 104 |
+
|
| 105 |
+
> π‘ 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.
|
| 106 |
+
|
| 107 |
+
### Step 7 β Run
|
| 108 |
+
|
| 109 |
+
```bash
|
| 110 |
+
pip install -r requirements.txt
|
| 111 |
+
python bot.py
|
| 112 |
+
```
|
| 113 |
+
|
| 114 |
+
---
|
| 115 |
+
|
| 116 |
+
## π οΈ Admin Commands (DM your bot)
|
| 117 |
+
|
| 118 |
+
| Command | What it does |
|
| 119 |
+
|---------|-------------|
|
| 120 |
+
| `/start` | Admin panel β active channels, job count, dashboard link |
|
| 121 |
+
| `/help` | Full admin guide |
|
| 122 |
+
| `/status` | All scheduled jobs grouped by channel with next run time |
|
| 123 |
+
| `/channels` | List channels; tap to pause/resume any channel |
|
| 124 |
+
| `/preview` | Interactive: pick channel β pick content type β see AI preview β post now |
|
| 125 |
+
| `/preview <channel_key> <type>` | Direct preview, e.g. `/preview jee_main formula_sheet` |
|
| 126 |
+
| `/coverage` | Chapter coverage % per channel β see how much syllabus has been covered |
|
| 127 |
+
| `/stats` | Rich analytics dashboard with progress bars per subject |
|
| 128 |
+
| `/mcq_session <channel_key>` | Manually trigger a 10-poll MCQ session |
|
| 129 |
+
| `/force_digest <channel_key>` | Immediately generate and send the weekly PDF |
|
| 130 |
+
| `/broadcast <message>` | Push a message to all registered users |
|
| 131 |
+
| `/set_time <type> <HH:MM>` | Change posting time, e.g. `/set_time short_notes 11:30` |
|
| 132 |
+
| `/add_channel <key> <id> <label>` | Register a new channel |
|
| 133 |
+
| `/del_channel <key>` | Remove a channel |
|
| 134 |
+
| `/healthcheck` | Test all subsystems: Gemini API, Scheduler, Gist, User DB, Error Log |
|
| 135 |
+
|
| 136 |
+
---
|
| 137 |
+
|
| 138 |
+
## π§ͺ MCQ Poll Session
|
| 139 |
+
|
| 140 |
+
Each session posts **10 quiz polls** to a channel with configurable delays:
|
| 141 |
+
|
| 142 |
+
- **Automatic:** Runs daily at 8:00 PM IST for MCQ-enabled channels
|
| 143 |
+
- **Manual:** `/mcq_session <channel_key>` or via the inline menu
|
| 144 |
+
- **Delay:** Configurable per channel (`mcq_poll_delay_min` / `mcq_poll_delay_max` in seconds)
|
| 145 |
+
- Each poll is a native Telegram Quiz Poll with the correct answer and explanation
|
| 146 |
+
|
| 147 |
+
```python
|
| 148 |
+
# In config, per channel:
|
| 149 |
+
"mcq_poll_enabled": True,
|
| 150 |
+
"mcq_poll_delay_min": 60, # seconds between polls
|
| 151 |
+
"mcq_poll_delay_max": 90,
|
| 152 |
+
```
|
| 153 |
+
|
| 154 |
+
---
|
| 155 |
+
|
| 156 |
+
## π Weekly PDF Digest (CrazyLearners Branding)
|
| 157 |
+
|
| 158 |
+
Every **Sunday at 9:00 PM IST**, the bot:
|
| 159 |
+
1. Compiles all **Short Notes** and **Formula Sheets** posted that week
|
| 160 |
+
2. Generates a branded PDF with:
|
| 161 |
+
- Cover page (CrazyLearners purple/teal design)
|
| 162 |
+
- Auto-generated Table of Contents
|
| 163 |
+
- Subject pill badges + Chapter cards
|
| 164 |
+
- Justified body text with sub-heading detection
|
| 165 |
+
- Page header/footer with brand name + `t.me/xcrazylearners`
|
| 166 |
+
- Back page with CTA (join our community)
|
| 167 |
+
3. Sends the PDF to each active channel with a branded caption
|
| 168 |
+
|
| 169 |
+
**Force a digest anytime:** `/force_digest <channel_key>`
|
| 170 |
+
|
| 171 |
+
---
|
| 172 |
+
|
| 173 |
+
## π« Repeat Prevention
|
| 174 |
+
|
| 175 |
+
The bot tracks the last **60 topics** per *(channel Γ content type Γ subject)* in `data/content_history.json`.
|
| 176 |
+
|
| 177 |
+
- Excludes all recently used chapters when picking a new topic
|
| 178 |
+
- If all chapters are used, picks from the **oldest half** (least recently used)
|
| 179 |
+
- Each channel maintains **independent history**
|
| 180 |
+
|
| 181 |
+
**Reset history:** `/coverage` β tap "Reset a channel's history"
|
| 182 |
+
|
| 183 |
+
**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.
|
| 184 |
+
|
| 185 |
+
---
|
| 186 |
+
|
| 187 |
+
## β Adding a New Channel
|
| 188 |
+
|
| 189 |
+
1. Create the Telegram channel
|
| 190 |
+
2. Add your bot as Admin with Post Messages permission
|
| 191 |
+
3. Use the bot command: `/add_channel <key> <@channel_id> <Label>`
|
| 192 |
+
Example: `/add_channel neet_2 @NEET_MyChannel "NEET Daily 2"`
|
| 193 |
+
4. Or add via the **Web Dashboard β Channel Manager**
|
| 194 |
+
|
| 195 |
+
The new channel is automatically scheduled β no restart needed.
|
| 196 |
+
|
| 197 |
+
---
|
| 198 |
+
|
| 199 |
+
## π Web Dashboard
|
| 200 |
+
|
| 201 |
+
The bot exposes a Flask/Gradio web dashboard for visual management:
|
| 202 |
+
|
| 203 |
+
- **Add/Delete/Toggle Channels**
|
| 204 |
+
- **Set posting schedules** (CRON-style)
|
| 205 |
+
- **Manage syllabus** (add subjects, chapters)
|
| 206 |
+
- **Trigger content** to any channel instantly
|
| 207 |
+
- **Edit AI prompts** for each content type
|
| 208 |
+
|
| 209 |
+
Dashboard URL: configured in `DEFAULT_SETTINGS["dashboard_url"]`
|
| 210 |
+
|
| 211 |
+
---
|
| 212 |
+
|
| 213 |
+
## π Deployment
|
| 214 |
+
|
| 215 |
+
### Hugging Face Spaces (Current)
|
| 216 |
+
The bot runs as a Docker Space. Set all env vars in **Settings β Variables and secrets**.
|
| 217 |
+
|
| 218 |
+
### Railway / Render
|
| 219 |
+
1. Push this folder to a GitHub repo
|
| 220 |
+
2. Connect to Railway or Render
|
| 221 |
+
3. Set env vars: `BOT_TOKEN`, `GEMINI_API_KEY`, `ADMIN_USER_IDS`
|
| 222 |
+
4. Deploy as a **Background Worker** (no open port needed)
|
| 223 |
+
|
| 224 |
+
### VPS / Self-hosted
|
| 225 |
+
```bash
|
| 226 |
+
screen -S jeebot
|
| 227 |
+
python bot.py
|
| 228 |
+
# Ctrl+A D to detach
|
| 229 |
+
```
|
| 230 |
+
|
| 231 |
+
---
|
| 232 |
+
|
| 233 |
+
## π Project Structure
|
| 234 |
+
|
| 235 |
+
```
|
| 236 |
+
JEE, NEET & Advance Content Manager/
|
| 237 |
+
βββ bot.py β Entry point; starts polling + dashboard server
|
| 238 |
+
βββ config.py β Env vars + Gemini settings (model, tokens, temp)
|
| 239 |
+
βββ requirements.txt
|
| 240 |
+
βββ data/
|
| 241 |
+
β βββ bot_config.json β Auto-saved dynamic config (channels, schedule)
|
| 242 |
+
β βββ content_history.json β Repeat-prevention tracker
|
| 243 |
+
β βββ syllabus.json β Full JEE/NEET syllabus (chapters per subject)
|
| 244 |
+
β βββ prompts.json β Custom AI prompt templates (editable via dashboard)
|
| 245 |
+
β βββ digests/ β Generated weekly PDF files
|
| 246 |
+
βββ content/
|
| 247 |
+
β βββ generator.py β Gemini AI content generation + Markdown sanitizer
|
| 248 |
+
β βββ history.py β Chapter tracker + weekly archive for PDFs
|
| 249 |
+
β βββ pdf_generator.py β Branded CrazyLearners PDF builder (fpdf2)
|
| 250 |
+
β βββ config_manager.py β Dynamic channel/schedule config (JSON-backed)
|
| 251 |
+
β βββ syllabus_manager.py β Syllabus loader with recursive chapter extraction
|
| 252 |
+
β βββ template_manager.py β AI prompt template manager
|
| 253 |
+
β βββ doubt_solver.py β Gemini-powered doubt answering for students
|
| 254 |
+
β βββ remote_storage.py β GitHub Gist sync for history persistence
|
| 255 |
+
β βββ user_registry.py β Registered user DB (for broadcast)
|
| 256 |
+
βββ scheduler/
|
| 257 |
+
β βββ job_scheduler.py β APScheduler: 1 job per (content_type Γ channel)
|
| 258 |
+
β _safe_send_message with Markdown parse recovery
|
| 259 |
+
βββ handlers/
|
| 260 |
+
βββ commands.py β /start /status /channels /preview /mcq_session etc.
|
| 261 |
+
βββ callbacks.py β Inline button actions (pause, preview, post-now)
|
| 262 |
+
βββ doubt_handler.py β DM + group @mention doubt handler
|
| 263 |
+
βββ menu_router.py β Routes reply-keyboard button taps
|
| 264 |
+
```
|
| 265 |
+
|
| 266 |
+
---
|
| 267 |
+
|
| 268 |
+
## π§ Key Configuration Constants (`config.py`)
|
| 269 |
+
|
| 270 |
+
| Constant | Default | Purpose |
|
| 271 |
+
|----------|---------|---------|
|
| 272 |
+
| `GEMINI_MODEL` | `gemini-2.0-flash` | Gemini model for all AI generation |
|
| 273 |
+
| `GEMINI_MAX_TOKENS` | `3500` | Max tokens per AI response (high enough for 10-MCQ JSON) |
|
| 274 |
+
| `GEMINI_TEMPERATURE` | `0.7` | Creativity vs consistency balance |
|
| 275 |
+
| `HISTORY_DEPTH` | `60` | How many past topics to remember before reuse is allowed |
|
| 276 |
+
|
| 277 |
+
---
|
| 278 |
+
|
| 279 |
+
## π Known Issues Fixed (v2.0)
|
| 280 |
+
|
| 281 |
+
| Bug | Fix |
|
| 282 |
+
|-----|-----|
|
| 283 |
+
| `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 |
|
| 284 |
+
| `Message is too long` | Hard 4000-char truncation in `_clean_markdown()` + `_safe_send_message()` |
|
| 285 |
+
| `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 |
|
| 286 |
+
| MCQ callback blocking event loop 15 min | `asyncio.create_task()` instead of `await` in callback handler |
|
| 287 |
+
| PDF file handle leak | Wrapped `send_document` in `with open(...) as f` |
|
| 288 |
+
| `KeyError` on custom content type in `/set_time` | Changed `CONTENT_LABELS[ctype]` β `.get(ctype, ctype)` |
|
| 289 |
+
| Broadcast hitting Telegram 429 rate limit | `asyncio.sleep(0.05)` between each send |
|
| 290 |
+
| `get_me()` API call on every group message | Cached in `context.bot_data` after first call |
|
| 291 |
+
| Archive storing empty date | Uses `datetime.now()` instead of missing env var |
|
| 292 |
+
| Preview command crashing on dict response | Handles quiz/text/error dict shapes correctly |
|
bot.py
CHANGED
|
@@ -104,7 +104,7 @@ class BotHandler(BaseHTTPRequestHandler):
|
|
| 104 |
if path == "/api/health":
|
| 105 |
import time
|
| 106 |
from scheduler.job_scheduler import get_all_jobs
|
| 107 |
-
from config import
|
| 108 |
|
| 109 |
# Basic subsystem check
|
| 110 |
scheduler_ok = True
|
|
@@ -116,8 +116,8 @@ class BotHandler(BaseHTTPRequestHandler):
|
|
| 116 |
"ts": time.strftime("%H:%M:%S"),
|
| 117 |
"checks": {
|
| 118 |
"scheduler": {"ok": scheduler_ok, "msg": f"{len(get_all_jobs())} jobs active" if scheduler_ok else "Scheduler error"},
|
| 119 |
-
"
|
| 120 |
-
"telegram":
|
| 121 |
}
|
| 122 |
})
|
| 123 |
return
|
|
|
|
| 104 |
if path == "/api/health":
|
| 105 |
import time
|
| 106 |
from scheduler.job_scheduler import get_all_jobs
|
| 107 |
+
from config import GEMINI_MODEL
|
| 108 |
|
| 109 |
# Basic subsystem check
|
| 110 |
scheduler_ok = True
|
|
|
|
| 116 |
"ts": time.strftime("%H:%M:%S"),
|
| 117 |
"checks": {
|
| 118 |
"scheduler": {"ok": scheduler_ok, "msg": f"{len(get_all_jobs())} jobs active" if scheduler_ok else "Scheduler error"},
|
| 119 |
+
"gemini": {"ok": True, "msg": f"Model: {GEMINI_MODEL}"},
|
| 120 |
+
"telegram": {"ok": True, "msg": "API Online"}
|
| 121 |
}
|
| 122 |
})
|
| 123 |
return
|
config.py
CHANGED
|
@@ -8,7 +8,7 @@ load_dotenv()
|
|
| 8 |
# βββββββββββββββββββββββββββββββββββββββββββββ
|
| 9 |
|
| 10 |
BOT_TOKEN = os.getenv("BOT_TOKEN", "YOUR_TELEGRAM_BOT_TOKEN") # From @BotFather
|
| 11 |
-
|
| 12 |
GIST_ID = os.getenv("GIST_ID", "") # GitHub Gist ID
|
| 13 |
GIST_TOKEN = os.getenv("GIST_TOKEN", "") # GitHub Personal Access Token
|
| 14 |
|
|
@@ -46,9 +46,9 @@ SUBJECT_ROTATION = {
|
|
| 46 |
}
|
| 47 |
|
| 48 |
# βββββββββββββββββββββββββββββββββββββββββββββ
|
| 49 |
-
#
|
| 50 |
# βββββββββββββββββββββββββββββββββββββββββββββ
|
| 51 |
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
|
|
|
| 8 |
# βββββββββββββββββββββββββββββββββββββββββββββ
|
| 9 |
|
| 10 |
BOT_TOKEN = os.getenv("BOT_TOKEN", "YOUR_TELEGRAM_BOT_TOKEN") # From @BotFather
|
| 11 |
+
GEMINI_API_KEY = os.getenv("GEMINI_API_KEY", "YOUR_GEMINI_API_KEY") # From Google AI Studio
|
| 12 |
GIST_ID = os.getenv("GIST_ID", "") # GitHub Gist ID
|
| 13 |
GIST_TOKEN = os.getenv("GIST_TOKEN", "") # GitHub Personal Access Token
|
| 14 |
|
|
|
|
| 46 |
}
|
| 47 |
|
| 48 |
# βββββββββββββββββββββββββββββββββββββββββββββ
|
| 49 |
+
# GEMINI SETTINGS
|
| 50 |
# βββββββββββββββββββββββββββββββββββββββββββββ
|
| 51 |
|
| 52 |
+
GEMINI_MODEL = "gemini-2.0-flash"
|
| 53 |
+
GEMINI_MAX_TOKENS = 4500 # Sufficient for large MCQ sessions with detailed explanations
|
| 54 |
+
GEMINI_TEMPERATURE = 0.7
|
content/doubt_solver.py
CHANGED
|
@@ -1,119 +1,123 @@
|
|
| 1 |
-
"""
|
| 2 |
-
AI Doubt Solver
|
| 3 |
-
Explains any JEE/NEET question, MCQ, or topic forwarded to the bot.
|
| 4 |
-
Works for: DM messages, group @mentions, replies-to-bot messages.
|
| 5 |
-
"""
|
| 6 |
-
|
| 7 |
-
import logging
|
| 8 |
-
import re
|
| 9 |
-
|
| 10 |
-
from
|
| 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 |
-
If it's
|
| 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 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
AI Doubt Solver
|
| 3 |
+
Explains any JEE/NEET question, MCQ, or topic forwarded to the bot.
|
| 4 |
+
Works for: DM messages, group @mentions, replies-to-bot messages.
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
import logging
|
| 8 |
+
import re
|
| 9 |
+
import google.generativeai as genai
|
| 10 |
+
from google.generativeai.types import GenerationConfig
|
| 11 |
+
from config import GEMINI_API_KEY, GEMINI_MODEL, GEMINI_MAX_TOKENS
|
| 12 |
+
|
| 13 |
+
logger = logging.getLogger(__name__)
|
| 14 |
+
genai.configure(api_key=GEMINI_API_KEY)
|
| 15 |
+
|
| 16 |
+
# System prompt that makes the bot act as a JEE/NEET tutor
|
| 17 |
+
_SYSTEM_PROMPT = (
|
| 18 |
+
"You are an expert JEE and NEET tutor named 'CrazyBot'. "
|
| 19 |
+
"Your job is to explain concepts, solve MCQs, and clear doubts for students preparing for JEE Main, "
|
| 20 |
+
"JEE Advanced, and NEET-UG. "
|
| 21 |
+
"When given a question or MCQ, you MUST:\n"
|
| 22 |
+
"1. Identify the topic/concept\n"
|
| 23 |
+
"2. Explain the core concept clearly in simple language\n"
|
| 24 |
+
"3. Show step-by-step solution if it's a numerical\n"
|
| 25 |
+
"4. State the correct answer with full reasoning\n"
|
| 26 |
+
"5. Give 1 exam tip related to this concept\n\n"
|
| 27 |
+
"Keep responses concise (max 400 words). Use Unicode math symbols (Β², β, Ο, ΞΌ, Ξ, ΞΈ). "
|
| 28 |
+
"No LaTeX. Format with emojis for readability on Telegram."
|
| 29 |
+
)
|
| 30 |
+
|
| 31 |
+
_DOUBT_PROMPT_TEMPLATE = """A JEE/NEET student has a doubt. Here is what they sent:
|
| 32 |
+
|
| 33 |
+
---
|
| 34 |
+
{content}
|
| 35 |
+
---
|
| 36 |
+
|
| 37 |
+
Please explain this clearly. If it's an MCQ, solve it step-by-step and reveal the correct answer.
|
| 38 |
+
If it's a concept question, explain it with an example and a JEE/NEET exam tip."""
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def _extract_text(message) -> str:
|
| 42 |
+
"""
|
| 43 |
+
Extract meaningful text from a Telegram message object.
|
| 44 |
+
Handles: plain text, forwarded text, poll questions, captions.
|
| 45 |
+
"""
|
| 46 |
+
parts = []
|
| 47 |
+
|
| 48 |
+
# Forwarded message context
|
| 49 |
+
if message.forward_origin or message.forward_date:
|
| 50 |
+
parts.append("[Forwarded content]")
|
| 51 |
+
|
| 52 |
+
# Poll forwarded
|
| 53 |
+
if message.poll:
|
| 54 |
+
poll = message.poll
|
| 55 |
+
parts.append(f"MCQ: {poll.question}")
|
| 56 |
+
for i, opt in enumerate(poll.options):
|
| 57 |
+
label = chr(65 + i) # A, B, C, D
|
| 58 |
+
parts.append(f"({label}) {opt.text}")
|
| 59 |
+
return "\n".join(parts)
|
| 60 |
+
|
| 61 |
+
# Regular text or caption
|
| 62 |
+
text = message.text or message.caption or ""
|
| 63 |
+
|
| 64 |
+
# Strip bot mention (@BotName) from group messages
|
| 65 |
+
text = re.sub(r'@\w+', '', text).strip()
|
| 66 |
+
|
| 67 |
+
if text:
|
| 68 |
+
parts.append(text)
|
| 69 |
+
|
| 70 |
+
return "\n".join(parts).strip() if parts else ""
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
async def solve_doubt(user_question: str) -> str:
|
| 74 |
+
"""
|
| 75 |
+
Call Gemini to explain/solve the student's question.
|
| 76 |
+
Returns formatted response string.
|
| 77 |
+
"""
|
| 78 |
+
if not user_question or len(user_question.strip()) < 5:
|
| 79 |
+
return (
|
| 80 |
+
"π€ *I need a question to answer!*\n\n"
|
| 81 |
+
"Please:\n"
|
| 82 |
+
"β’ Type your doubt directly\n"
|
| 83 |
+
"β’ Forward any MCQ or question to me\n"
|
| 84 |
+
"β’ Reply to a question in the group mentioning me\n\n"
|
| 85 |
+
"Example: `What is Bernoulli's principle?`"
|
| 86 |
+
)
|
| 87 |
+
|
| 88 |
+
prompt = _DOUBT_PROMPT_TEMPLATE.format(content=user_question[:2000])
|
| 89 |
+
|
| 90 |
+
try:
|
| 91 |
+
from content.config_manager import config_manager
|
| 92 |
+
s = config_manager.settings
|
| 93 |
+
system_prompt = _SYSTEM_PROMPT.replace("CrazyBot", s['bot_name'])
|
| 94 |
+
|
| 95 |
+
model = genai.GenerativeModel(
|
| 96 |
+
model_name=GEMINI_MODEL,
|
| 97 |
+
system_instruction=system_prompt
|
| 98 |
+
)
|
| 99 |
+
|
| 100 |
+
response = await model.generate_content_async(
|
| 101 |
+
prompt,
|
| 102 |
+
generation_config=GenerationConfig(
|
| 103 |
+
max_output_tokens=GEMINI_MAX_TOKENS,
|
| 104 |
+
temperature=0.5,
|
| 105 |
+
)
|
| 106 |
+
)
|
| 107 |
+
answer = response.text
|
| 108 |
+
if not answer:
|
| 109 |
+
return "β οΈ I couldn't generate a response right now. Please try again."
|
| 110 |
+
|
| 111 |
+
# Add helpful footer
|
| 112 |
+
answer = answer.strip()
|
| 113 |
+
answer += f"\n\nββββββββββββββ\nπ *[{s['main_channel_name']}]({s['main_channel_url']})* | Ask more doubts anytime!"
|
| 114 |
+
return answer
|
| 115 |
+
|
| 116 |
+
except Exception as e:
|
| 117 |
+
logger.error(f"[DoubtSolver] Gemini error: {e}")
|
| 118 |
+
from content.config_manager import config_manager
|
| 119 |
+
s = config_manager.settings
|
| 120 |
+
return (
|
| 121 |
+
"β οΈ *Doubt solver is temporarily unavailable.*\n"
|
| 122 |
+
f"Please try again in a moment, or check [{s['main_channel_name']}]({s['main_channel_url']}) for help."
|
| 123 |
+
)
|
content/generator.py
CHANGED
|
@@ -1,516 +1,521 @@
|
|
| 1 |
-
import logging
|
| 2 |
-
import random
|
| 3 |
-
import traceback
|
| 4 |
-
import asyncio
|
| 5 |
-
import json
|
| 6 |
-
import re
|
| 7 |
-
from datetime import datetime
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
from content.
|
| 16 |
-
from content.
|
| 17 |
-
from content.
|
| 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 |
-
temp = re.sub(r'`
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
temp2 = re.sub(r'`
|
| 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 |
-
return {"
|
| 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 |
-
|
| 297 |
-
|
| 298 |
-
|
| 299 |
-
|
| 300 |
-
|
| 301 |
-
|
| 302 |
-
|
| 303 |
-
|
| 304 |
-
|
| 305 |
-
|
| 306 |
-
|
| 307 |
-
|
| 308 |
-
|
| 309 |
-
|
| 310 |
-
|
| 311 |
-
|
| 312 |
-
|
| 313 |
-
|
| 314 |
-
|
| 315 |
-
|
| 316 |
-
|
| 317 |
-
|
| 318 |
-
|
| 319 |
-
|
| 320 |
-
|
| 321 |
-
|
| 322 |
-
|
| 323 |
-
|
| 324 |
-
|
| 325 |
-
|
| 326 |
-
|
| 327 |
-
|
| 328 |
-
|
| 329 |
-
|
| 330 |
-
|
| 331 |
-
|
| 332 |
-
|
| 333 |
-
|
| 334 |
-
|
| 335 |
-
|
| 336 |
-
|
| 337 |
-
|
| 338 |
-
|
| 339 |
-
|
| 340 |
-
|
| 341 |
-
|
| 342 |
-
|
| 343 |
-
|
| 344 |
-
|
| 345 |
-
|
| 346 |
-
|
| 347 |
-
|
| 348 |
-
|
| 349 |
-
|
| 350 |
-
|
| 351 |
-
|
| 352 |
-
|
| 353 |
-
|
| 354 |
-
|
| 355 |
-
|
| 356 |
-
|
| 357 |
-
|
| 358 |
-
|
| 359 |
-
|
| 360 |
-
|
| 361 |
-
|
| 362 |
-
|
| 363 |
-
|
| 364 |
-
|
| 365 |
-
|
| 366 |
-
|
| 367 |
-
|
| 368 |
-
|
| 369 |
-
|
| 370 |
-
|
| 371 |
-
|
| 372 |
-
|
| 373 |
-
|
| 374 |
-
|
| 375 |
-
|
| 376 |
-
|
| 377 |
-
|
| 378 |
-
|
| 379 |
-
|
| 380 |
-
|
| 381 |
-
|
| 382 |
-
|
| 383 |
-
|
| 384 |
-
|
| 385 |
-
|
| 386 |
-
|
| 387 |
-
|
| 388 |
-
|
| 389 |
-
|
| 390 |
-
|
| 391 |
-
|
| 392 |
-
|
| 393 |
-
|
| 394 |
-
|
| 395 |
-
|
| 396 |
-
|
| 397 |
-
|
| 398 |
-
|
| 399 |
-
|
| 400 |
-
|
| 401 |
-
|
| 402 |
-
|
| 403 |
-
|
| 404 |
-
|
| 405 |
-
|
| 406 |
-
|
| 407 |
-
|
| 408 |
-
|
| 409 |
-
|
| 410 |
-
|
| 411 |
-
|
| 412 |
-
|
| 413 |
-
|
| 414 |
-
|
| 415 |
-
|
| 416 |
-
|
| 417 |
-
|
| 418 |
-
|
| 419 |
-
|
| 420 |
-
|
| 421 |
-
|
| 422 |
-
|
| 423 |
-
if not
|
| 424 |
-
|
| 425 |
-
|
| 426 |
-
|
| 427 |
-
|
| 428 |
-
|
| 429 |
-
|
| 430 |
-
|
| 431 |
-
|
| 432 |
-
|
| 433 |
-
|
| 434 |
-
|
| 435 |
-
|
| 436 |
-
|
| 437 |
-
|
| 438 |
-
|
| 439 |
-
|
| 440 |
-
|
| 441 |
-
|
| 442 |
-
|
| 443 |
-
|
| 444 |
-
|
| 445 |
-
|
| 446 |
-
|
| 447 |
-
|
| 448 |
-
|
| 449 |
-
|
| 450 |
-
|
| 451 |
-
|
| 452 |
-
|
| 453 |
-
|
| 454 |
-
|
| 455 |
-
|
| 456 |
-
|
| 457 |
-
|
| 458 |
-
|
| 459 |
-
|
| 460 |
-
|
| 461 |
-
|
| 462 |
-
|
| 463 |
-
|
| 464 |
-
|
| 465 |
-
|
| 466 |
-
|
| 467 |
-
|
| 468 |
-
"
|
| 469 |
-
"
|
| 470 |
-
"
|
| 471 |
-
|
| 472 |
-
|
| 473 |
-
|
| 474 |
-
"
|
| 475 |
-
"
|
| 476 |
-
|
| 477 |
-
|
| 478 |
-
|
| 479 |
-
"
|
| 480 |
-
"
|
| 481 |
-
"
|
| 482 |
-
|
| 483 |
-
|
| 484 |
-
|
| 485 |
-
|
| 486 |
-
"""
|
| 487 |
-
|
| 488 |
-
|
| 489 |
-
|
| 490 |
-
|
| 491 |
-
|
| 492 |
-
|
| 493 |
-
|
| 494 |
-
|
| 495 |
-
|
| 496 |
-
|
| 497 |
-
|
| 498 |
-
|
| 499 |
-
|
| 500 |
-
|
| 501 |
-
|
| 502 |
-
|
| 503 |
-
|
| 504 |
-
|
| 505 |
-
|
| 506 |
-
|
| 507 |
-
|
| 508 |
-
|
| 509 |
-
|
| 510 |
-
|
| 511 |
-
|
| 512 |
-
|
| 513 |
-
|
| 514 |
-
|
| 515 |
-
|
| 516 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import logging
|
| 2 |
+
import random
|
| 3 |
+
import traceback
|
| 4 |
+
import asyncio
|
| 5 |
+
import json
|
| 6 |
+
import re
|
| 7 |
+
from datetime import datetime
|
| 8 |
+
import google.generativeai as genai
|
| 9 |
+
from google.generativeai.types import GenerationConfig
|
| 10 |
+
|
| 11 |
+
from config import (
|
| 12 |
+
GEMINI_API_KEY, GEMINI_MODEL, GEMINI_MAX_TOKENS,
|
| 13 |
+
GEMINI_TEMPERATURE, SUBJECT_ROTATION
|
| 14 |
+
)
|
| 15 |
+
from content.config_manager import config_manager
|
| 16 |
+
from content.syllabus_manager import syllabus_manager
|
| 17 |
+
from content.template_manager import template_manager
|
| 18 |
+
from content.history import pick_fresh_chapter, archive_weekly_post
|
| 19 |
+
|
| 20 |
+
logger = logging.getLogger(__name__)
|
| 21 |
+
|
| 22 |
+
# Initialize Gemini Client
|
| 23 |
+
genai.configure(api_key=GEMINI_API_KEY)
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
# βββββββββββββββββββββββββββββββββββββββββββββ
|
| 27 |
+
# Helpers
|
| 28 |
+
# βββββββββββββββββββββββββββββββββββββββββββββ
|
| 29 |
+
|
| 30 |
+
def _clean_markdown(text: str) -> str:
|
| 31 |
+
"""
|
| 32 |
+
Cleanup to prevent Telegram Markdown parse errors.
|
| 33 |
+
Handles unclosed code blocks, bold, italic, and inline-code markers.
|
| 34 |
+
Also enforces the 4096-character Telegram message limit.
|
| 35 |
+
"""
|
| 36 |
+
if not text:
|
| 37 |
+
return ""
|
| 38 |
+
|
| 39 |
+
# --- 1. Close unclosed triple-backtick code blocks ---
|
| 40 |
+
if text.count("```") % 2 != 0:
|
| 41 |
+
text += "\n```"
|
| 42 |
+
|
| 43 |
+
# --- 2. Close unclosed inline backtick spans ---
|
| 44 |
+
if text.count("`") % 2 != 0:
|
| 45 |
+
text += "`"
|
| 46 |
+
|
| 47 |
+
# --- 3. Close unclosed bold markers (*) ---
|
| 48 |
+
# Only count * that are NOT part of *** or ** patterns
|
| 49 |
+
# Simple heuristic: strip code blocks first, then count remaining *
|
| 50 |
+
temp = re.sub(r'```.*?```', '', text, flags=re.DOTALL) # remove code blocks
|
| 51 |
+
temp = re.sub(r'`[^`]*`', '', temp) # remove inline code
|
| 52 |
+
if temp.count("*") % 2 != 0:
|
| 53 |
+
text += "*"
|
| 54 |
+
|
| 55 |
+
# --- 4. Close unclosed italic underscores (_) outside code spans ---
|
| 56 |
+
temp2 = re.sub(r'```.*?```', '', text, flags=re.DOTALL)
|
| 57 |
+
temp2 = re.sub(r'`[^`]*`', '', temp2)
|
| 58 |
+
if temp2.count("_") % 2 != 0:
|
| 59 |
+
text += "\_"
|
| 60 |
+
|
| 61 |
+
# --- 5. Truncate to Telegram's 4096-char hard limit ---
|
| 62 |
+
if len(text) > 4000:
|
| 63 |
+
text = text[:3997] + "..."
|
| 64 |
+
|
| 65 |
+
return text
|
| 66 |
+
|
| 67 |
+
def _today() -> str:
|
| 68 |
+
return datetime.now().strftime("%A")
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
async def _call_gemini(prompt: str) -> str:
|
| 72 |
+
"""Wrapper for Gemini API calls with retry logic for rate limits."""
|
| 73 |
+
max_retries = 3
|
| 74 |
+
base_delay = 2 # Gemini free tier might need some delay on rate limits
|
| 75 |
+
|
| 76 |
+
for attempt in range(max_retries):
|
| 77 |
+
try:
|
| 78 |
+
model = genai.GenerativeModel(
|
| 79 |
+
model_name=GEMINI_MODEL,
|
| 80 |
+
system_instruction=template_manager.system_prompt
|
| 81 |
+
)
|
| 82 |
+
response = await model.generate_content_async(
|
| 83 |
+
prompt,
|
| 84 |
+
generation_config=GenerationConfig(
|
| 85 |
+
max_output_tokens=GEMINI_MAX_TOKENS,
|
| 86 |
+
temperature=GEMINI_TEMPERATURE,
|
| 87 |
+
)
|
| 88 |
+
)
|
| 89 |
+
|
| 90 |
+
content = response.text
|
| 91 |
+
if not content:
|
| 92 |
+
logger.warning(f"Gemini returned empty response (Attempt {attempt+1}/{max_retries})")
|
| 93 |
+
if attempt < max_retries - 1:
|
| 94 |
+
await asyncio.sleep(base_delay * (2 ** attempt))
|
| 95 |
+
continue
|
| 96 |
+
return None
|
| 97 |
+
|
| 98 |
+
return _clean_markdown(content.strip())
|
| 99 |
+
|
| 100 |
+
except Exception as e:
|
| 101 |
+
err_msg = str(e).lower()
|
| 102 |
+
# Handle rate limits
|
| 103 |
+
if "429" in err_msg or "quota" in err_msg or "rate" in err_msg:
|
| 104 |
+
wait_time = base_delay * (2 ** attempt) + 2
|
| 105 |
+
logger.warning(f"Gemini Rate Limit hit. Retrying in {wait_time:.1f}s... (Attempt {attempt+1}/{max_retries})")
|
| 106 |
+
if attempt < max_retries - 1:
|
| 107 |
+
import asyncio
|
| 108 |
+
await asyncio.sleep(wait_time)
|
| 109 |
+
continue
|
| 110 |
+
|
| 111 |
+
logger.error(f"Gemini API error: {e}
|
| 112 |
+
{traceback.format_exc()}")
|
| 113 |
+
return None
|
| 114 |
+
|
| 115 |
+
return None
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
def _channel_subjects(channel_key: str) -> list:
|
| 119 |
+
"""Return subjects active for this channel on today's rotation, filtered by syllabus availability."""
|
| 120 |
+
channel_cfg = config_manager.channels.get(channel_key, {})
|
| 121 |
+
exam_focus = channel_cfg.get("exam_focus", ["JEE Main"])
|
| 122 |
+
|
| 123 |
+
# Get all subjects available in the syllabus for this exam
|
| 124 |
+
all_syllabus_subjects = set()
|
| 125 |
+
for focus in exam_focus:
|
| 126 |
+
all_syllabus_subjects.update(syllabus_manager.get_all_subjects(focus))
|
| 127 |
+
|
| 128 |
+
ch_subjects = set(channel_cfg.get("subjects", list(all_syllabus_subjects)))
|
| 129 |
+
day_subjects = set(SUBJECT_ROTATION.get(_today(), list(all_syllabus_subjects)))
|
| 130 |
+
active = list(ch_subjects & day_subjects)
|
| 131 |
+
return active if active else list(ch_subjects)
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
def _pick(channel_key: str, content_type: str) -> tuple:
|
| 135 |
+
"""Pick a non-repeating (subject, chapter) pair for this channel + content type."""
|
| 136 |
+
subjects = _channel_subjects(channel_key)
|
| 137 |
+
subject = random.choice(subjects)
|
| 138 |
+
chapter = pick_fresh_chapter(channel_key, content_type, subject)
|
| 139 |
+
return subject, chapter
|
| 140 |
+
|
| 141 |
+
|
| 142 |
+
def _footer(channel_key: str, tag_key: str) -> str:
|
| 143 |
+
cfg = config_manager.channels.get(channel_key, {})
|
| 144 |
+
footer = cfg.get("footer", "β¨ *Study Hard, Score High!*")
|
| 145 |
+
hashtag = cfg.get("hashtags", {}).get(tag_key, "")
|
| 146 |
+
|
| 147 |
+
brand = "π *Join for more:* @xcrazylearners"
|
| 148 |
+
sep = "ββββββββββββββββββ"
|
| 149 |
+
|
| 150 |
+
if hashtag:
|
| 151 |
+
return f"\n\n{hashtag}\n{sep}\n{footer}\n{brand}"
|
| 152 |
+
else:
|
| 153 |
+
return f"\n\n{sep}\n{footer}\n{brand}"
|
| 154 |
+
|
| 155 |
+
|
| 156 |
+
def _exam(channel_key: str) -> str:
|
| 157 |
+
exams = config_manager.channels.get(channel_key, {}).get("exam_focus", ["JEE Main"])
|
| 158 |
+
return random.choice(exams)
|
| 159 |
+
|
| 160 |
+
def _difficulty_context(channel_key: str) -> str:
|
| 161 |
+
"""Returns a difficulty instruction based on the channel's target exams."""
|
| 162 |
+
cfg = config_manager.channels.get(channel_key, {})
|
| 163 |
+
exams = cfg.get("exam_focus", [])
|
| 164 |
+
|
| 165 |
+
# Class 9/10 focus
|
| 166 |
+
if any(ex in ["Class 9", "Class 10", "NTSE", "Foundation"] for ex in exams):
|
| 167 |
+
return "Difficulty: Foundation/School Level. Focus on basic concepts, definitions, and clear logic. Avoid extremely complex calculus or advanced topics."
|
| 168 |
+
|
| 169 |
+
# JEE Advanced focus
|
| 170 |
+
if "JEE Advanced" in exams:
|
| 171 |
+
return "Difficulty: Advanced/Hard. Use multi-concept problems, challenging numericals, and tricky logic. Focus on deep understanding."
|
| 172 |
+
|
| 173 |
+
# JEE Main / NEET focus (default for competitive)
|
| 174 |
+
return "Difficulty: Competitive (JEE Main/NEET level). Focus on accuracy, speed-based patterns, and standard competitive concepts."
|
| 175 |
+
|
| 176 |
+
|
| 177 |
+
# βββββββββββββββββββββββββββββββββββββββββββββ
|
| 178 |
+
# 1. PYQ QUESTION (QUIZ MODE)
|
| 179 |
+
# βββββββββββββββββββββββββββββββββββββββββββββ
|
| 180 |
+
|
| 181 |
+
def _parse_quiz(text: str) -> dict:
|
| 182 |
+
"""Extracts quiz components from the AI-generated text."""
|
| 183 |
+
try:
|
| 184 |
+
# Question: Find text between β QUESTION: and (A)
|
| 185 |
+
q_start = text.find("β QUESTION:") + len("β QUESTION:")
|
| 186 |
+
q_end = text.find("(A)")
|
| 187 |
+
question = text[q_start:q_end].strip()
|
| 188 |
+
|
| 189 |
+
# Truncate question for Telegram (300 chars limit)
|
| 190 |
+
if len(question) > 297:
|
| 191 |
+
question = question[:297] + "..."
|
| 192 |
+
|
| 193 |
+
# Options: (A), (B), (C), (D)
|
| 194 |
+
options = []
|
| 195 |
+
for label in ["(A)", "(B)", "(C)", "(D)"]:
|
| 196 |
+
start = text.find(label) + len(label)
|
| 197 |
+
# Find the next label or the answer line
|
| 198 |
+
next_label = text.find("(B)") if label == "(A)" else (text.find("(C)") if label == "(B)" else (text.find("(D)") if label == "(C)" else text.find("||β
ANSWER:")))
|
| 199 |
+
opt_text = text[start:next_label].strip()
|
| 200 |
+
options.append(opt_text[:100]) # Telegram limit: 100 chars per option
|
| 201 |
+
|
| 202 |
+
# Correct Answer Index
|
| 203 |
+
ans_line = text.lower().find("answer: (")
|
| 204 |
+
correct_letter = text[ans_line + len("answer: (") : ans_line + len("answer: (") + 1].upper()
|
| 205 |
+
mapping = {"A": 0, "B": 1, "C": 2, "D": 3}
|
| 206 |
+
correct_index = mapping.get(correct_letter, 0)
|
| 207 |
+
|
| 208 |
+
# Explanation
|
| 209 |
+
e_start = text.find("π‘ EXPLANATION:") + len("π‘ EXPLANATION:")
|
| 210 |
+
e_end = text.find("π― Difficulty:")
|
| 211 |
+
explanation = text[e_start:e_end].strip()
|
| 212 |
+
|
| 213 |
+
# Truncate explanation for Telegram (200 chars limit)
|
| 214 |
+
if len(explanation) > 197:
|
| 215 |
+
explanation = explanation[:197] + "..."
|
| 216 |
+
|
| 217 |
+
return {
|
| 218 |
+
"question": question,
|
| 219 |
+
"options": options,
|
| 220 |
+
"correct_index": correct_index,
|
| 221 |
+
"explanation": explanation,
|
| 222 |
+
"full_text": text # Still include the full text for fallback/preview
|
| 223 |
+
}
|
| 224 |
+
except Exception as e:
|
| 225 |
+
logger.error(f"Quiz parsing failed: {e}")
|
| 226 |
+
return None
|
| 227 |
+
|
| 228 |
+
|
| 229 |
+
async def generate_pyq_question(channel_key: str) -> dict:
|
| 230 |
+
subject, chapter = _pick(channel_key, "pyq_question")
|
| 231 |
+
exam = _exam(channel_key)
|
| 232 |
+
year = random.randint(2015, 2023)
|
| 233 |
+
|
| 234 |
+
template = template_manager.get_template("pyq_question")
|
| 235 |
+
diff_text = _difficulty_context(channel_key)
|
| 236 |
+
prompt = template.format(
|
| 237 |
+
exam=exam, year=year, chapter=chapter,
|
| 238 |
+
subject=subject.title()
|
| 239 |
+
) + f"\n\n{diff_text}"
|
| 240 |
+
|
| 241 |
+
raw_text = await _call_gemini(prompt)
|
| 242 |
+
if not raw_text:
|
| 243 |
+
return {"error": "β οΈ Content temporarily unavailable."}
|
| 244 |
+
|
| 245 |
+
quiz_data = _parse_quiz(raw_text)
|
| 246 |
+
if not quiz_data:
|
| 247 |
+
# Fallback to plain text if parsing fails
|
| 248 |
+
return {"text": raw_text + _footer(channel_key, "pyq")}
|
| 249 |
+
|
| 250 |
+
# Return structured dict for the dispatcher
|
| 251 |
+
return {
|
| 252 |
+
"text": raw_text + _footer(channel_key, "pyq"),
|
| 253 |
+
"quiz": quiz_data,
|
| 254 |
+
"type": "quiz"
|
| 255 |
+
}
|
| 256 |
+
|
| 257 |
+
|
| 258 |
+
# βββββββββββββββββββββββββββββββββββββββββββββ
|
| 259 |
+
# 2. FORMULA SHEET
|
| 260 |
+
# βββββββββββββββββββββββββββββββββββββββββββββ
|
| 261 |
+
|
| 262 |
+
async def generate_formula_sheet(channel_key: str) -> str:
|
| 263 |
+
subject, chapter = _pick(channel_key, "formula_sheet")
|
| 264 |
+
exam = _exam(channel_key)
|
| 265 |
+
|
| 266 |
+
template = template_manager.get_template("formula_sheet")
|
| 267 |
+
prompt = template.format(exam=exam, chapter=chapter, subject=subject.title())
|
| 268 |
+
|
| 269 |
+
text = await _call_gemini(prompt)
|
| 270 |
+
text = (text or "β οΈ Content temporarily unavailable.")
|
| 271 |
+
|
| 272 |
+
# Archive for Weekly PDF
|
| 273 |
+
if text != "β οΈ Content temporarily unavailable.":
|
| 274 |
+
archive_weekly_post(channel_key, "formula_sheet", subject, chapter, text)
|
| 275 |
+
|
| 276 |
+
return text + _footer(channel_key, "formula")
|
| 277 |
+
|
| 278 |
+
|
| 279 |
+
# βββββββββββββββββββββββββββββββββββββββββββββ
|
| 280 |
+
# 3. SHORT NOTES
|
| 281 |
+
# βββββββββββββββββββββββββββββββββββββββββββββ
|
| 282 |
+
|
| 283 |
+
async def generate_short_notes(channel_key: str) -> str:
|
| 284 |
+
subject, chapter = _pick(channel_key, "short_notes")
|
| 285 |
+
exam = _exam(channel_key)
|
| 286 |
+
|
| 287 |
+
template = template_manager.get_template("short_notes")
|
| 288 |
+
prompt = template.format(exam=exam, chapter=chapter, subject=subject.title())
|
| 289 |
+
|
| 290 |
+
text = await _call_gemini(prompt)
|
| 291 |
+
text = (text or "β οΈ Content temporarily unavailable.")
|
| 292 |
+
|
| 293 |
+
# Archive for Weekly PDF
|
| 294 |
+
if text != "β οΈ Content temporarily unavailable.":
|
| 295 |
+
archive_weekly_post(channel_key, "short_notes", subject, chapter, text)
|
| 296 |
+
|
| 297 |
+
return text + _footer(channel_key, "notes")
|
| 298 |
+
|
| 299 |
+
|
| 300 |
+
# βββββββββββββββββββββββββββββββββββββββββββββ
|
| 301 |
+
# 4. MNEMONIC
|
| 302 |
+
# βββββββββββββββββββββββββββββββββββββββββββββ
|
| 303 |
+
|
| 304 |
+
async def generate_mnemonic(channel_key: str) -> str:
|
| 305 |
+
subject, chapter = _pick(channel_key, "mnemonic")
|
| 306 |
+
|
| 307 |
+
template = template_manager.get_template("mnemonic")
|
| 308 |
+
prompt = template.format(chapter=chapter, subject=subject.title())
|
| 309 |
+
|
| 310 |
+
text = await _call_gemini(prompt)
|
| 311 |
+
return (text or "β οΈ Content temporarily unavailable.") + _footer(channel_key, "mnemonic")
|
| 312 |
+
|
| 313 |
+
|
| 314 |
+
# βββββββββββββββββββββββββββββββββββββββββββββ
|
| 315 |
+
# 5. CONCEPT RECAP
|
| 316 |
+
# βββββββββββββββββββββββββββββββββββββββββββββ
|
| 317 |
+
|
| 318 |
+
async def generate_concept_recap(channel_key: str) -> str:
|
| 319 |
+
subject, chapter = _pick(channel_key, "concept_recap")
|
| 320 |
+
exam = _exam(channel_key)
|
| 321 |
+
|
| 322 |
+
template = template_manager.get_template("concept_recap")
|
| 323 |
+
prompt = template.format(exam=exam, chapter=chapter, subject=subject.title())
|
| 324 |
+
|
| 325 |
+
text = await _call_gemini(prompt)
|
| 326 |
+
return (text or "β οΈ Content temporarily unavailable.") + _footer(channel_key, "recap")
|
| 327 |
+
|
| 328 |
+
|
| 329 |
+
# βββββββββββββββββββββββββββββββββββββββββββββ
|
| 330 |
+
# 6. MOCK MCQ
|
| 331 |
+
# βββββββββββββββββββββββββββββββββββββββββββββ
|
| 332 |
+
|
| 333 |
+
async def generate_mock_question(channel_key: str) -> str:
|
| 334 |
+
subject, chapter = _pick(channel_key, "mock_question")
|
| 335 |
+
exam = _exam(channel_key)
|
| 336 |
+
|
| 337 |
+
template = template_manager.get_template("mock_question")
|
| 338 |
+
diff_text = _difficulty_context(channel_key)
|
| 339 |
+
prompt = template.format(exam=exam, chapter=chapter, subject=subject.title()) + f"\n\n{diff_text}"
|
| 340 |
+
|
| 341 |
+
text = await _call_gemini(prompt)
|
| 342 |
+
return (text or "β οΈ Content temporarily unavailable.") + _footer(channel_key, "mock")
|
| 343 |
+
|
| 344 |
+
|
| 345 |
+
# βββββββββββββββββββββββββββββββββββββββββββββ
|
| 346 |
+
# 7. MOTIVATIONAL
|
| 347 |
+
# βββββββββββββββββββββββββββββββββββββββββββββ
|
| 348 |
+
|
| 349 |
+
async def generate_motivational(channel_key: str) -> str:
|
| 350 |
+
exam = _exam(channel_key)
|
| 351 |
+
|
| 352 |
+
# Pick a random subject and chapter to make the message specific
|
| 353 |
+
subjects = _channel_subjects(channel_key)
|
| 354 |
+
subject = random.choice(subjects)
|
| 355 |
+
chapter = pick_fresh_chapter(channel_key, "motivational", subject)
|
| 356 |
+
|
| 357 |
+
template = template_manager.get_template("motivational")
|
| 358 |
+
prompt = template.format(exam=exam, subject=subject.title(), chapter=chapter)
|
| 359 |
+
|
| 360 |
+
text = await _call_gemini(prompt)
|
| 361 |
+
cfg = config_manager.channels.get(channel_key, {})
|
| 362 |
+
footer = cfg.get("footer", "")
|
| 363 |
+
return (text or "π Rest well! See you tomorrow πͺ") + (f"\n\n{footer}" if footer else "")
|
| 364 |
+
|
| 365 |
+
|
| 366 |
+
# βββββββββββββββββββββββββββββββββββββββββββββ
|
| 367 |
+
# 8. MCQ POLL SESSION (10 polls, chapter-wise)
|
| 368 |
+
# βββββββββββββββββββββββββββββββββββββββββββββ
|
| 369 |
+
|
| 370 |
+
def _parse_mcq_json(text: str) -> list:
|
| 371 |
+
"""Extract and repair a JSON array of MCQ dicts from the Gemini response."""
|
| 372 |
+
if not text: return []
|
| 373 |
+
|
| 374 |
+
# 1. Basic Cleaning
|
| 375 |
+
clean = text.strip()
|
| 376 |
+
if clean.startswith("```"):
|
| 377 |
+
clean = re.sub(r'^```(?:json)?\s*', '', clean, flags=re.MULTILINE)
|
| 378 |
+
clean = re.sub(r'\s*```\s*$', '', clean, flags=re.MULTILINE).strip()
|
| 379 |
+
|
| 380 |
+
# 2. Slice to array bounds if possible
|
| 381 |
+
start = clean.find('[')
|
| 382 |
+
if start == -1: return []
|
| 383 |
+
|
| 384 |
+
# Try to find the last ']' - but if it's truncated, we might need to repair it
|
| 385 |
+
end = clean.rfind(']')
|
| 386 |
+
|
| 387 |
+
candidate = clean[start:]
|
| 388 |
+
if end != -1:
|
| 389 |
+
candidate = clean[start:end + 1]
|
| 390 |
+
|
| 391 |
+
# 3. Progressive Repair Strategy
|
| 392 |
+
try:
|
| 393 |
+
return json.loads(candidate)
|
| 394 |
+
except json.JSONDecodeError:
|
| 395 |
+
# AI truncated mid-object? Let's try to fix it.
|
| 396 |
+
# Strategy: Remove everything after the last valid "}," and add "]"
|
| 397 |
+
last_comma = candidate.rfind('},')
|
| 398 |
+
if last_comma != -1:
|
| 399 |
+
try:
|
| 400 |
+
return json.loads(candidate[:last_comma + 1] + "]")
|
| 401 |
+
except: pass
|
| 402 |
+
|
| 403 |
+
# Try finding the last "}" and closing the array
|
| 404 |
+
last_brace = candidate.rfind('}')
|
| 405 |
+
if last_brace != -1:
|
| 406 |
+
try:
|
| 407 |
+
return json.loads(candidate[:last_brace + 1] + "]")
|
| 408 |
+
except: pass
|
| 409 |
+
|
| 410 |
+
return []
|
| 411 |
+
|
| 412 |
+
|
| 413 |
+
async def generate_mcq_session(channel_key: str) -> dict:
|
| 414 |
+
"""Generate 10 MCQ Telegram quiz polls for a single chapter."""
|
| 415 |
+
subject, chapter = _pick(channel_key, "mcq_session")
|
| 416 |
+
exam = _exam(channel_key)
|
| 417 |
+
|
| 418 |
+
template = template_manager.get_template("mcq_session")
|
| 419 |
+
diff_text = _difficulty_context(channel_key)
|
| 420 |
+
prompt = template.format(exam=exam, chapter=chapter, subject=subject.title()) + f"\n\n{diff_text}"
|
| 421 |
+
|
| 422 |
+
raw = await _call_gemini(prompt)
|
| 423 |
+
if not raw:
|
| 424 |
+
return {"error": "β οΈ MCQ Session content temporarily unavailable."}
|
| 425 |
+
|
| 426 |
+
questions = _parse_mcq_json(raw)
|
| 427 |
+
MIN_MCQ = 3 # Accept sessions with at least 3 valid questions
|
| 428 |
+
if not questions or len(questions) < MIN_MCQ:
|
| 429 |
+
logger.warning(f"MCQ session got only {len(questions)} questions (need {MIN_MCQ}) β retrying once")
|
| 430 |
+
# --- One automatic retry before giving up ---
|
| 431 |
+
raw2 = await _call_gemini(prompt)
|
| 432 |
+
if raw2:
|
| 433 |
+
questions = _parse_mcq_json(raw2)
|
| 434 |
+
if not questions or len(questions) < MIN_MCQ:
|
| 435 |
+
logger.error(f"MCQ session still only {len(questions)} questions after retry β giving up")
|
| 436 |
+
return {"error": "β οΈ Could not generate enough MCQs right now. Please retry."}
|
| 437 |
+
|
| 438 |
+
# Clamp to exactly 10
|
| 439 |
+
questions = questions[:10]
|
| 440 |
+
|
| 441 |
+
# Sanitise each question for Telegram limits
|
| 442 |
+
clean = []
|
| 443 |
+
for q in questions:
|
| 444 |
+
opts = [str(o)[:100] for o in q.get("options", [])]
|
| 445 |
+
if len(opts) < 4:
|
| 446 |
+
continue # skip malformed
|
| 447 |
+
clean.append({
|
| 448 |
+
"question": str(q.get("question", ""))[:300],
|
| 449 |
+
"options": opts,
|
| 450 |
+
"correct_index": int(q.get("correct_index", 0)) % 4,
|
| 451 |
+
"explanation": str(q.get("explanation", ""))[:200],
|
| 452 |
+
})
|
| 453 |
+
|
| 454 |
+
return {
|
| 455 |
+
"type": "mcq_session",
|
| 456 |
+
"subject": subject,
|
| 457 |
+
"chapter": chapter,
|
| 458 |
+
"exam": exam,
|
| 459 |
+
"questions": clean,
|
| 460 |
+
}
|
| 461 |
+
|
| 462 |
+
|
| 463 |
+
# βββββββββββββββββββββββββββββββββββββββββββββ
|
| 464 |
+
# DISPATCHER
|
| 465 |
+
# βββββββββββββββββββββββββββββββββββββββββββββ
|
| 466 |
+
|
| 467 |
+
CONTENT_GENERATORS = {
|
| 468 |
+
"pyq_question": generate_pyq_question,
|
| 469 |
+
"formula_sheet": generate_formula_sheet,
|
| 470 |
+
"short_notes": generate_short_notes,
|
| 471 |
+
"mnemonic": generate_mnemonic,
|
| 472 |
+
"concept_recap": generate_concept_recap,
|
| 473 |
+
"mock_question": generate_mock_question,
|
| 474 |
+
"motivational": generate_motivational,
|
| 475 |
+
"mcq_session": generate_mcq_session,
|
| 476 |
+
}
|
| 477 |
+
|
| 478 |
+
CONTENT_LABELS = {
|
| 479 |
+
"pyq_question": "π
Daily PYQ Question",
|
| 480 |
+
"formula_sheet": "π Formula Sheet",
|
| 481 |
+
"short_notes": "π Short Notes",
|
| 482 |
+
"mnemonic": "π§ Memory Tricks",
|
| 483 |
+
"concept_recap": "π
Concept Recap",
|
| 484 |
+
"mock_question": "π― Daily Mock",
|
| 485 |
+
"motivational": "π Night Motivation",
|
| 486 |
+
"mcq_session": "π§ͺ MCQ Poll Session",
|
| 487 |
+
}
|
| 488 |
+
|
| 489 |
+
|
| 490 |
+
async def generate_generic_ai_post(content_type: str, channel_key: str) -> dict:
|
| 491 |
+
"""Fallback generator for user-defined custom content types."""
|
| 492 |
+
prompt_template = template_manager.data["templates"].get(content_type)
|
| 493 |
+
if not prompt_template:
|
| 494 |
+
return {"text": f"β No prompt template found for custom type: `{content_type}`"}
|
| 495 |
+
|
| 496 |
+
subject, chapter = _pick(channel_key, content_type)
|
| 497 |
+
exam = _exam(channel_key)
|
| 498 |
+
year = datetime.now().year
|
| 499 |
+
|
| 500 |
+
try:
|
| 501 |
+
full_prompt = prompt_template.format(exam=exam, subject=subject, chapter=chapter, year=year)
|
| 502 |
+
except KeyError as e:
|
| 503 |
+
# Fallback if user uses a placeholder we don't have
|
| 504 |
+
full_prompt = prompt_template
|
| 505 |
+
logger.warning(f"Template for {content_type} has unknown placeholder {e}")
|
| 506 |
+
|
| 507 |
+
text = await _call_gemini(full_prompt)
|
| 508 |
+
if not text:
|
| 509 |
+
return {"error": "Gemini failed to generate text."}
|
| 510 |
+
|
| 511 |
+
return {
|
| 512 |
+
"text": _clean_markdown(text) + _footer(channel_key, content_type)
|
| 513 |
+
}
|
| 514 |
+
|
| 515 |
+
|
| 516 |
+
async def generate_content(content_type: str, channel_key: str) -> str:
|
| 517 |
+
gen = CONTENT_GENERATORS.get(content_type)
|
| 518 |
+
if not gen:
|
| 519 |
+
# Try generic generator for custom types
|
| 520 |
+
return await generate_generic_ai_post(content_type, channel_key)
|
| 521 |
+
return await gen(channel_key)
|
handlers/commands.py
CHANGED
|
@@ -498,21 +498,21 @@ async def healthcheck_command(update: Update, context: ContextTypes.DEFAULT_TYPE
|
|
| 498 |
except Exception as e:
|
| 499 |
results.append(f"β *Scheduler:* FAILED β `{e}`")
|
| 500 |
|
| 501 |
-
# βββ 2.
|
| 502 |
try:
|
| 503 |
-
|
| 504 |
-
from
|
| 505 |
-
|
| 506 |
-
|
| 507 |
-
|
| 508 |
-
|
| 509 |
-
|
| 510 |
-
temperature=0
|
| 511 |
)
|
| 512 |
-
reply = test.
|
| 513 |
-
results.append(f"β
*
|
| 514 |
except Exception as e:
|
| 515 |
-
results.append(f"β *
|
| 516 |
|
| 517 |
# βββ 3. Gist / Remote Storage βββ
|
| 518 |
try:
|
|
|
|
| 498 |
except Exception as e:
|
| 499 |
results.append(f"β *Scheduler:* FAILED β `{e}`")
|
| 500 |
|
| 501 |
+
# βββ 2. Gemini API βββ
|
| 502 |
try:
|
| 503 |
+
import google.generativeai as genai
|
| 504 |
+
from google.generativeai.types import GenerationConfig
|
| 505 |
+
from config import GEMINI_API_KEY, GEMINI_MODEL
|
| 506 |
+
genai.configure(api_key=GEMINI_API_KEY)
|
| 507 |
+
model = genai.GenerativeModel(GEMINI_MODEL)
|
| 508 |
+
test = await model.generate_content_async(
|
| 509 |
+
"Reply with just: OK",
|
| 510 |
+
generation_config=GenerationConfig(max_output_tokens=5, temperature=0.0)
|
| 511 |
)
|
| 512 |
+
reply = test.text.strip()
|
| 513 |
+
results.append(f"β
*Gemini API:* Online β Model: `{GEMINI_MODEL}` β Reply: `{reply}`")
|
| 514 |
except Exception as e:
|
| 515 |
+
results.append(f"β *Gemini API:* FAILED β `{str(e)[:80]}`")
|
| 516 |
|
| 517 |
# βββ 3. Gist / Remote Storage βββ
|
| 518 |
try:
|
refactor.py
ADDED
|
@@ -0,0 +1,69 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import sys
|
| 2 |
+
import re
|
| 3 |
+
|
| 4 |
+
file = 'content/generator.py'
|
| 5 |
+
with open(file, 'r', encoding='utf-8') as f:
|
| 6 |
+
code = f.read()
|
| 7 |
+
|
| 8 |
+
code = code.replace('from groq import AsyncGroq', 'import google.generativeai as genai\nfrom google.generativeai.types import GenerationConfig')
|
| 9 |
+
code = code.replace('GROQ_API_KEY, GROQ_MODEL, GROQ_MAX_TOKENS,', 'GEMINI_API_KEY, GEMINI_MODEL, GEMINI_MAX_TOKENS,')
|
| 10 |
+
code = code.replace('GROQ_TEMPERATURE, SUBJECT_ROTATION', 'GEMINI_TEMPERATURE, SUBJECT_ROTATION')
|
| 11 |
+
code = code.replace('# Initialize Groq Client\nclient = AsyncGroq(api_key=GROQ_API_KEY)', '# Initialize Gemini Client\ngenai.configure(api_key=GEMINI_API_KEY)')
|
| 12 |
+
code = code.replace('_call_groq', '_call_gemini')
|
| 13 |
+
|
| 14 |
+
old_func_pattern = re.compile(r'async def _call_gemini\(prompt: str\) -> str:.*?(?=\ndef _channel_subjects)', re.DOTALL)
|
| 15 |
+
new_func = """async def _call_gemini(prompt: str) -> str:
|
| 16 |
+
\"\"\"Wrapper for Gemini API calls with retry logic for rate limits.\"\"\"
|
| 17 |
+
max_retries = 3
|
| 18 |
+
base_delay = 2 # Gemini free tier might need some delay on rate limits
|
| 19 |
+
|
| 20 |
+
for attempt in range(max_retries):
|
| 21 |
+
try:
|
| 22 |
+
model = genai.GenerativeModel(
|
| 23 |
+
model_name=GEMINI_MODEL,
|
| 24 |
+
system_instruction=template_manager.system_prompt
|
| 25 |
+
)
|
| 26 |
+
response = await model.generate_content_async(
|
| 27 |
+
prompt,
|
| 28 |
+
generation_config=GenerationConfig(
|
| 29 |
+
max_output_tokens=GEMINI_MAX_TOKENS,
|
| 30 |
+
temperature=GEMINI_TEMPERATURE,
|
| 31 |
+
)
|
| 32 |
+
)
|
| 33 |
+
|
| 34 |
+
content = response.text
|
| 35 |
+
if not content:
|
| 36 |
+
logger.warning(f"Gemini returned empty response (Attempt {attempt+1}/{max_retries})")
|
| 37 |
+
if attempt < max_retries - 1:
|
| 38 |
+
await asyncio.sleep(base_delay * (2 ** attempt))
|
| 39 |
+
continue
|
| 40 |
+
return None
|
| 41 |
+
|
| 42 |
+
return _clean_markdown(content.strip())
|
| 43 |
+
|
| 44 |
+
except Exception as e:
|
| 45 |
+
err_msg = str(e).lower()
|
| 46 |
+
# Handle rate limits
|
| 47 |
+
if "429" in err_msg or "quota" in err_msg or "rate" in err_msg:
|
| 48 |
+
wait_time = base_delay * (2 ** attempt) + 2
|
| 49 |
+
logger.warning(f"Gemini Rate Limit hit. Retrying in {wait_time:.1f}s... (Attempt {attempt+1}/{max_retries})")
|
| 50 |
+
if attempt < max_retries - 1:
|
| 51 |
+
import asyncio
|
| 52 |
+
await asyncio.sleep(wait_time)
|
| 53 |
+
continue
|
| 54 |
+
|
| 55 |
+
logger.error(f"Gemini API error: {e}\\n{traceback.format_exc()}")
|
| 56 |
+
return None
|
| 57 |
+
|
| 58 |
+
return None
|
| 59 |
+
|
| 60 |
+
"""
|
| 61 |
+
code = old_func_pattern.sub(new_func, code)
|
| 62 |
+
# Fix remaining Groq terms in logging/comments EXCEPT in imports if any
|
| 63 |
+
code = code.replace('Groq', 'Gemini').replace('groq', 'gemini')
|
| 64 |
+
code = code.replace('import google.geminiativeai as genai', 'import google.generativeai as genai')
|
| 65 |
+
code = code.replace('from google.geminiativeai.types', 'from google.generativeai.types')
|
| 66 |
+
|
| 67 |
+
with open(file, 'w', encoding='utf-8') as f:
|
| 68 |
+
f.write(code)
|
| 69 |
+
print("generator.py refactored!")
|
requirements.txt
CHANGED
|
@@ -2,6 +2,6 @@ python-telegram-bot>=20.0
|
|
| 2 |
apscheduler>=3.10.0
|
| 3 |
pytz
|
| 4 |
python-dotenv
|
| 5 |
-
|
| 6 |
requests
|
| 7 |
fpdf2>=2.7.0
|
|
|
|
| 2 |
apscheduler>=3.10.0
|
| 3 |
pytz
|
| 4 |
python-dotenv
|
| 5 |
+
google-generativeai>=0.5.2
|
| 6 |
requests
|
| 7 |
fpdf2>=2.7.0
|
verify_gemini.py
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import sys
|
| 3 |
+
from dotenv import load_dotenv
|
| 4 |
+
|
| 5 |
+
# Ensure packages are findable
|
| 6 |
+
sys.path.append(os.getcwd())
|
| 7 |
+
|
| 8 |
+
load_dotenv()
|
| 9 |
+
|
| 10 |
+
import asyncio
|
| 11 |
+
from content.generator import generate_content
|
| 12 |
+
|
| 13 |
+
print("Testing content generation with Groq...")
|
| 14 |
+
try:
|
| 15 |
+
# Attempt to generate a PYQ for jee_main
|
| 16 |
+
result = asyncio.run(generate_content("pyq_question", "jee_main"))
|
| 17 |
+
if isinstance(result, dict) and ("error" in result or "β οΈ" in str(result)):
|
| 18 |
+
print("β Generation failed. Check logs.")
|
| 19 |
+
print(result)
|
| 20 |
+
elif isinstance(result, str) and ("β οΈ" in result or "β" in result):
|
| 21 |
+
print("β Generation failed. Check logs.")
|
| 22 |
+
print(result)
|
| 23 |
+
else:
|
| 24 |
+
print("β
Groq generation successful!")
|
| 25 |
+
print("-" * 30)
|
| 26 |
+
# Print string or text content of dict
|
| 27 |
+
text_content = result.get("text", str(result)) if isinstance(result, dict) else result
|
| 28 |
+
print(text_content[:300] + "...")
|
| 29 |
+
except Exception as e:
|
| 30 |
+
print(f"β Critical error during test: {e}")
|
web_app/dashboard.html
CHANGED
|
@@ -1340,7 +1340,7 @@ async function runHealthCheck() {
|
|
| 1340 |
const iconOk = 'β
'; const iconErr = 'β';
|
| 1341 |
const rows = Object.entries(d.checks).map(([name, r]) => `
|
| 1342 |
<div class="health-row">
|
| 1343 |
-
<div><div class="health-label">${{
|
| 1344 |
<div class="health-msg">${r.msg}</div></div>
|
| 1345 |
<span style="font-size:20px">${r.ok ? iconOk : iconErr}</span>
|
| 1346 |
</div>`).join('');
|
|
|
|
| 1340 |
const iconOk = 'β
'; const iconErr = 'β';
|
| 1341 |
const rows = Object.entries(d.checks).map(([name, r]) => `
|
| 1342 |
<div class="health-row">
|
| 1343 |
+
<div><div class="health-label">${{gemini:'π€ Gemini AI',scheduler:'π
Scheduler',telegram:'π± Telegram API'}[name]||name}</div>
|
| 1344 |
<div class="health-msg">${r.msg}</div></div>
|
| 1345 |
<span style="font-size:20px">${r.ok ? iconOk : iconErr}</span>
|
| 1346 |
</div>`).join('');
|