Spaces:
Running
Download README.md from H3y-sam/Telegram-Bot: direct link, hf CLI and curl.
- Browser
- Download file 13 kB
-
https://huggingface.co/spaces/H3y-sam/Telegram-Bot/resolve/main/README.md
- Command line
-
hf download hf://spaces/H3y-sam/Telegram-Bot/README.md
-
curl -L -o README.md https://huggingface.co/spaces/H3y-sam/Telegram-Bot/resolve/main/README.md
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
β¨ 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
- Message @BotFather β
/newbot - Copy the API token
Step 2 β Get Gemini API Key
- Go to aistudio.google.com/app/apikey
- Sign up β API Keys β Create API Key
- Free tier is sufficient (model:
gemini-2.0-flash)
Step 3 β Create Channels & Add Bot as Admin
For each channel:
- Create the channel in Telegram
- Channel Settings β Administrators β Add Admin
- 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):
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:
"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.jsonand can be edited via the Web Dashboard without touching code.
Step 7 β Run
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_maxin seconds) - Each poll is a native Telegram Quiz Poll with the correct answer and explanation
# 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:
- Compiles all Short Notes and Formula Sheets posted that week
- 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)
- 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
Create the Telegram channel
Add your bot as Admin with Post Messages permission
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.
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
- Push this folder to a GitHub repo
- Connect to Railway or Render
- Set env vars:
BOT_TOKEN,GEMINI_API_KEY,ADMIN_USER_IDS - Deploy as a Background Worker (no open port needed)
VPS / Self-hosted
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 |