"""The admin manual: EVERY command with what it does, why you would use it, and an example. One registry feeds three things, so they can never disagree: * /help (the full manual, split into messages that fit Telegram's size limit) * the "/" menu (Telegram shows these commands as suggestions in your chat) * a unit test (fails if a command exists in the bot but is missing here) No imports from the rest of the app: this module is pure text and is tested without Telegram.""" import html from dataclasses import dataclass DEFAULT_FACTS = dict( prizes_enabled=True, prizes=[50, 30, 20], raffle=10, min_days=4, min_xp=40, contrib_xp=20, contrib_bonus=5, contrib_cap=5, daily_cap=25, ref_join=5, ref_qualified=30, ref_weekly=5, ) LIMIT = 3800 # a Telegram message holds 4096 characters; stay clear of the edge @dataclass(frozen=True) class Cmd: name: str usage: str what: str why: str tip: str = "" short: str = "" # one line for Telegram's "/" menu (max ~100 characters) def _e(text: str) -> str: return html.escape(text, quote=False) # only & < > need escaping for Telegram's HTML def sections(f: dict) -> list[tuple[str, str, list[Cmd]]]: prizes = " / ".join(str(p) for p in f["prizes"]) return [ ("1) Basics (everyone can use these)", "", [ Cmd("start", "/start or t.me/YourBot?start=TAG", "Opens the bot: join check, choosing stream and year, then the main menu. A start link can carry a " "payload: ?start=dorm5 (a tracking tag), ?start= (a friend's invite), ?start=c12 (opens " "course 12), ?start=f40 (opens file 40).", "Every poster, group and shared link is just a start link, so this is how new students arrive " "and how you measure where they came from.", "A link opened before the student has joined the channel is remembered and opened right after " "onboarding.", "Open the bot / main menu"), Cmd("help", "/help", "For you (admin): this manual. For students: a short guide to the buttons.", "One place to look up anything without remembering it.", "", "Admin manual / student guide"), Cmd("rules", "/rules", "Shows students the XP rules, the weekly contest and the fair-play policy.", "What you announce publicly must match what the bot says. This is the single source of truth.", "Link to it from your channel announcement (/announce does).", "XP, weekly contest and fair-play rules"), Cmd("find", "/find physics (used inside a class group)", "Searches the library from inside a group. The result is a list of buttons that open the course or " "file in the bot (private chat).", "Every classmate who taps a result must pass the join check and onboarding, so one search in a " "group can bring in many new students.", "Add the bot to class and department groups. It never reads group messages, it only answers /find.", "Search the library (in groups)"), ]), ("2) Courses", "Courses are the folders files are sorted into.", [ Cmd("courses", "/courses", "Lists every course with its id, stream, year and code.", "You need the ids for /upload, /move, /delcourse. Students never see courses without files.", "", "List courses with ids"), Cmd("addcourse", "/addcourse ", "Adds a course. Example: /addcourse natural 1 Chem1012 Organic Chemistry. Use - when there is no " "code, 0 for 'all years', 'all' for both streams.", "Lets you grow the catalogue beyond the built-in freshman list (second year, electives).", "Add the course BEFORE uploading its files so the smart upload can sort into it.", "Add a course"), Cmd("delcourse", "/delcourse [move_files_to_id]", "Deletes a course. If it still has files it refuses, unless you give a second id: the files move " "there first.", "Removes wrong or duplicate courses without ever losing a file.", "", "Delete a course"), Cmd("emptycourses", "/emptycourses", "Lists courses that have no files and offers a button to delete them all.", "Cleans the catalogue. Students already do not see empty courses, so this is optional.", "Deleted courses come back with /seedcourses, but until then new files for them cannot be sorted " "automatically. Usually it is better to keep them.", "List/delete courses without files"), Cmd("seedcourses", "/seedcourses", "Adds the built-in year-1 courses (DBU catalogue where known, national list otherwise, plus a " "'Freshman Guide and General Resources' bucket). Safe to run twice.", "Gives the smart upload something to sort into on day one.", "Run /mergecourses first if you ever had both streams seeded separately.", "Add the built-in year-1 courses"), Cmd("mergecourses", "/mergecourses", "Merges courses taken by both streams (English, Psychology...) that were stored twice, moving " "their files.", "One file belongs to one course, so a shared course must exist only once.", "Run it once, then /seedcourses.", "Merge duplicate courses"), ]), ("3) Files (uploading and fixing)", "SMART UPLOAD (no command): just send or forward files to the bot. For each one it reads the first " "pages, finds the course, kind (slide/exam/note/book) and a clean title, skips exact duplicates, flags " "near-duplicates (with buttons: keep both / replace / delete), asks you when unsure, and stamps PDFs " "with the channel link. Every reply names the file it is about.", [ Cmd("upload", "/upload ", "Forces every following file into one course and kind (silent bulk mode: one thumbs-up per file).", "Fastest way to load a whole folder when you already know where it belongs.", "Duplicate and watermark checks still run. Finish with /done.", "Bulk-upload into one course"), Cmd("done", "/done", "Ends /upload mode and reports how many files were saved or skipped.", "Gets you back to smart upload.", "", "End bulk-upload mode"), Cmd("recent", "/recent", "Shows the last 15 files: id, course, kind, title.", "Quick check that the smart upload sorted a batch correctly.", "Spot a mistake? Fix it with /move, /kind or /rename.", "Last 15 files"), Cmd("review", "/review", "Lists files the bot could not place (no course).", "Nothing stays lost: unsure files wait here, hidden from students.", "Fix each with /move .", "Files waiting for a course"), Cmd("move", "/move [slide|exam|note|book]", "Moves a file to another course, optionally changing its kind, and publishes it.", "Corrects a wrong or missing course in one line.", "", "Move a file to a course"), Cmd("kind", "/kind ", "Changes only the kind of a file.", "When the course is right but the type is not (a module marked as an exam).", "", "Change a file's kind"), Cmd("rename", "/rename ", "Sets a new title.", "Titles are what students read on the buttons.", "", "Rename a file"), Cmd("del", "/del ", "Deletes a file.", "Removes wrong or unwanted files.", "It cannot be undone.", "Delete a file"), Cmd("rewatermark", "/rewatermark [n]", "Stamps the channel link on PDFs saved before the watermark existed (n at a time, default 15).", "Every PDF a student receives then carries your channel, so shared files advertise you.", "Needs files up to 20 MB. Run it again until it says all are stamped.", "Stamp older PDFs with the channel link"), ]), ("4) Student contributions", "Students send files from the 'Contribute a file' button; nothing is visible " "to others until you approve it.", [ Cmd("queue", "/queue", "Opens the review queue, one card at a time. Each card shows who sent it, the file, the proposed " "course, kind and title and any warning. Buttons: Accept, Course (suggestions or all courses), " "Reject (pick a reason: duplicate / low quality / not allowed), Replace #N (when it is a better " "version of an existing file), Skip.", "Turns student help into library growth with about 3 taps per file. You get ONE summary message " f"when new files arrive (with a 'Review now' button), not one message per file.", f"Accepting stamps the PDF, publishes it and gives the student +{f['contrib_xp']} XP " f"(+{f['contrib_bonus']} if the course is short of files, max {f['contrib_cap']} rewarded files a week) " "and a badge at 1, 5 and 15 approved files. Rejecting tells them why; 3 rejections in 14 days " "pause their uploads for 7 days.", "Review student files"), ]), ("5) XP, weekly season and prizes", f"XP: daily check-in 3-7, download +1, invite +{f['ref_join']} when a friend joins and " f"+{f['ref_qualified']} when they become active (max {f['ref_weekly']} a week), contributions above. " f"Automatic XP is capped at {f['daily_cap']} a day. Every XP is written to an unchangeable ledger.", [ Cmd("season", "/season", "Live standings of the current week from the ledger: XP, active days, trust score and warning " "flags (referral-heavy, low-trust, new-account), and who is eligible.", "Watch the contest and spot suspicious accounts before the week closes.", "", "Live weekly standings"), Cmd("winners", "/winners", "Shows the last closed season: winners, raffle winner, prize amounts and payment status.", "This is your payment list.", f"Prizes: {prizes} birr mobile cards + {f['raffle']} birr raffle." if f["prizes_enabled"] else "Prizes are currently OFF.", "Last closed season (who to pay)"), Cmd("closeweek", "/closeweek 2026W41", "Closes a finished week right now instead of waiting for the automatic close.", "Useful for testing, or if the automatic close was missed.", "The bot closes the previous week by itself within ~10 minutes after Monday 00:00 Ethiopian time " "and sends you the summary.", "Close a finished week now"), Cmd("give", "/give ", "Gives a student extra XP (logged in the ledger as 'admin').", "Reward a great contribution, fix a mistake or run a manual promotion.", "", "Give XP to a student"), Cmd("trust", "/trust ", "Raises or lowers a student's trust score (0-100). Below 70 they cannot win prizes.", "Your tool against cheating: act when /season shows a flag.", "Every change is logged.", "Change a student's trust score"), ]), ("6) Growth and the channel", "", [ Cmd("growth", "/growth", "New students per day (7 days) and, for each source (poster, inline, referral, group, tags), how " "many joined, passed the join check, finished onboarding and were still active after 3 days. Also " "how many groups use the bot.", "Shows which posters and groups really work, so you repeat those and drop the rest.", "A new trackable link is any link t.me/YourBot?start=anything.", "Where new students come from"), Cmd("poster", "/poster [tag]", "Makes a printable A4 poster (PDF) with a QR code, plus the QR as two PNG images (white and " "transparent background). The tag names the place: /poster dorm5, /poster cafeteria.", "Offline marketing you can measure: each place has its own tag in /growth. The PNGs let you use " "your own design (for example in Canva).", "Test-scan the QR with a phone before printing and keep it at least 3 cm wide.", "Poster + QR for printing"), Cmd("analyze", "/analyze", "Your analytics screen with buttons: Overview, Growth (per day, funnel, sources, who is stuck), " "Retention (daily actives, who comes back), Library (files, downloads, empty courses and the searches " "that found NOTHING), Student files, Channel posts and Insights (what to do next, with the numbers).", "Turns the bot's own data into decisions: what material to add, where students are lost, which posts " "bring students. Every insight shows the numbers behind it.", "Channel views and shares are only visible in the Telegram app (the Bot API does not give them to bots). " "The bot records new channel posts and their reactions by itself; FORWARD an older text post to the bot to " "add it. Small samples (under ~30 students) are only hints.", "Analytics: growth, retention, library, insights"), Cmd("announce", "/announce", "Writes the channel announcement for the XP, levels and weekly prizes from your current settings, " "shows a preview and offers a button to post it to the channel.", "Your announcement always matches what the bot really does.", "Prizes are only mentioned when they are switched on.", "Write/post the channel announcement"), ]), ("7) System", "", [ Cmd("stats", "/stats", "Totals: users, how many passed the join check, onboarded, active today, " "referrals, courses, files, downloads and files waiting for review.", "A quick health check of the whole project.", "", "Key numbers"), Cmd("ping", "/ping", "Measures database and Telegram speed in milliseconds.", "Tells you whether slowness comes from the code, the database or Telegram.", "", "Database and Telegram speed"), Cmd("gatecheck", "/gatecheck", "Checks that the bot is ADMIN in every join-gate channel or group.", "If it is not, students are blocked (and you get an alert). Run this after any change to the channel or forum.", "", "Is the join-gate working?"), Cmd("admin", "/admin", "Same as /help.", "Older shortcut.", "", "Same as /help"), ]), ] def settings_text(f: dict) -> str: return ( "8) Settings (Hugging Face Space → Settings → Secrets)\n" "BOT_TOKEN, DATABASE_URL: required.\n" "ADMIN_IDS: your Telegram id(s), comma separated.\n" "GATE_CHANNELS: places students must join (default: the channel and the forum).\n" "LIBRARY_CHANNEL_ID: private channel that stores the stamped PDFs (backup).\n" "PRIZES_ENABLED (default true), PRIZE_TOP (default 50,30,20), PRIZE_RAFFLE (10), MIN_WEEK_XP (40), " "MIN_ACTIVE_DAYS (4).\n" "CONTRIBUTIONS_ENABLED, CONTRIBUTION_XP (20), CONTRIBUTION_BONUS_XP (5), CONTRIBUTION_WEEKLY_CAP (5), " "CONTRIBUTION_MIN_DAYS (2), CONTRIBUTION_PENDING_LIMIT (5), CONTRIBUTION_DAILY_LIMIT (8).\n" "WATERMARK_ENABLED, WATERMARK_TEXT, WATERMARK_URL, WATERMARK_DIAGONAL.\n" "HIDE_EMPTY_COURSES (default true).\n" "A change takes effect after the Space restarts (it restarts by itself when you edit a secret)." ) def playbook_text(f: dict) -> str: return ( "9) Routine\n" "Daily (2 minutes): /queue to review student files, /recent after you upload, /stats for a glance.\n" "Every Monday: the bot sends you the closed week by itself. Look at the flags (/winners), contact " "the winners on Telegram and pay the mobile cards. The bot has already told them they won.\n" "Every few days: /growth to see what works; make a new /poster for each new place.\n" "When something feels slow or broken: /ping, then /gatecheck.\n" "Adding material: forward files to the bot. Fix mistakes with /move, /kind, /rename, /del." ) def _fmt(c: Cmd) -> str: lines = [ f"/{c.name}", f"{_e(c.usage)}", f"• What it does: {_e(c.what)}", f"• Why use it: {_e(c.why)}", ] if c.tip: lines.append(f"• Note: {_e(c.tip)}") return "\n".join(lines) def render(facts: dict | None = None) -> list[str]: """The whole manual as messages that each fit in one Telegram message.""" f = {**DEFAULT_FACTS, **(facts or {})} blocks: list[str] = ["📖 ADMIN MANUAL\nEvery command, what it does and why you would use it."] for title, intro, cmds in sections(f): header = f"━━ {_e(title)} ━━" + (f"\n{_e(intro)}" if intro else "") blocks.append(header) blocks.extend(_fmt(c) for c in cmds) blocks.append(settings_text(f)) blocks.append(playbook_text(f)) messages, current = [], "" for block in blocks: if current and len(current) + len(block) + 2 > LIMIT: messages.append(current) current = "" current = f"{current}\n\n{block}" if current else block messages.append(current) return messages def all_command_names(facts: dict | None = None) -> set[str]: return {c.name for _, _, cmds in sections({**DEFAULT_FACTS, **(facts or {})}) for c in cmds} def menu_commands(names: set[str] | None = None) -> list[tuple[str, str]]: """(command, short description) for Telegram's "/" menu.""" out = [] for _, _, cmds in sections(DEFAULT_FACTS): for c in cmds: if names is None or c.name in names: out.append((c.name, (c.short or c.what)[:100])) return out def announcement_text(f: dict, bot_username: str) -> str: f = {**DEFAULT_FACTS, **f} lines = [ "🚀 DBU Freshman Bot: study smarter, earn rewards", "", "📚 Slides, modules and past exams for your courses, free and in one place.", f"👉 @{bot_username}", "", "⭐ EARN XP", "• Open the bot every day: 3-7 XP (keep your streak!)", "• Download a file: +1 XP", f"• Invite a friend: +{f['ref_join']} XP when they join, +{f['ref_qualified']} XP when they become an active student", f"• Share a useful file: +{f['contrib_xp']} XP when it is approved (+{f['contrib_bonus']} for courses that need files)", ] if f["prizes_enabled"]: medals = ["🥇", "🥈", "🥉"] + ["🏅"] * 7 prize_line = " ".join(f"{medals[i]} {p} birr" for i, p in enumerate(f["prizes"])) lines += [ "", "🏆 WEEKLY PRIZES (Monday to Sunday, Ethiopian time)", f"{prize_line} (mobile card)", f"🎟 Plus a {f['raffle']} birr raffle for another qualified student.", f"To qualify: be active {f['min_days']}+ days in the week, earn {f['min_xp']}+ XP and stay in the channel and the forum.", ] lines += [ "", "🏅 Levels from Freshman to Legend, plus contributor badges.", "Fair play: every XP is recorded; fake accounts are removed. Full rules: /rules in the bot.", ] return "\n".join(lines)