Telegram-Bot / README.md
H3y-sam's picture
Upload 54 files
add04fc verified
|
Raw History Blame Contribute Delete
13 kB
metadata
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

  1. Message @BotFather β†’ /newbot
  2. Copy the API token

Step 2 β€” Get Gemini API Key

  1. Go to 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):

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.json and 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_max in 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:

  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

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