Skip to content
Sajad Raad
Mechatronics Engineering · Stage 3 · UoB
Back to Selected Work
CASE STUDY // REF: MECHA-BOT·Implemented & Tested
Telegram Bot Systems & Academic Platforms · Year 2026

Mecha-Bot Monorepo

High-Concurrency Telegram Bot, Interactive Mini-App & Academic IR Engine

CI Tests Passing
582 Tests
Telegram Clients
Bot + Mini-App (TMA)
Search Algorithm
BM25 + Semantic
Architecture
Turborepo / pnpm
TypeScriptNode.js 22Telegram WebApp APITurborepo / pnpmaiogram / grammYBM25 SearchCloudflare Workers
01

Project Overview

Mecha-Bot is a specialized academic infrastructure platform built specifically for the Mechatronics Engineering department at the University of Basrah (هندسة الميكاترونكس — جامعة البصرة). It unifies four years of specialized engineering syllabi, lecture slides, mathematical formula sheets, and past examination papers into a responsive high-concurrency Telegram Bot, interactive Telegram Mini-App (TMA), and scheduled background workers.

02

Problem and Motivation

Mechatronics Engineering students navigate a demanding interdisciplinary curriculum spanning mechanical dynamics, microprocessors, control theory, analog electronics, and programming. Academic materials were historically fragmented across disparate cloud drives, informal chat channels, and untracked PDFs. Finding specific exam formulas or verifying timetable lecture changes during the semester was cumbersome and error-prone. Mecha-Bot was built to give every student an authoritative, instant, verified knowledge retrieval system in their pocket via high-throughput Telegram bot interfaces.

03

Requirements and Constraints

  • ■Complete structural representation of Stages 1, 2, 3, and 4 Mechatronics curricula.
  • ■Deterministic low-latency search capable of running efficiently in memory or on edge runtimes (Cloudflare Workers / Node.js).
  • ■Dual client interfaces: an instant command-line style Telegram Bot and an interactive visual Telegram Mini-App for schedule exploration.
  • ■Strict type safety and monorepo modularity so individual packages can be updated or tested in isolation.
  • ■High test coverage: no breaking changes to curriculum routing or timetable matrices allowed into production.
04

My Role & Contributions

  • ›Built high-throughput asynchronous Telegram bot pipelines and Webhook endpoints with secret token validation.
  • ›Engineered interactive Telegram Mini-App (TMA) interfaces integrated with dynamic schedule matrices and WebApp SDK.
  • ›Implemented the custom in-memory BM25 lexical ranking engine in TypeScript for instant lecture querying.
  • ›Curated and indexed the official academic curriculum across all 4 stages of the University of Basrah Mechatronics department.
  • ›Authored the complete 582-test automated CI validation harness.
05

System Architecture

The codebase is divided into independent packages and deployable applications managed via Turborepo.

MECHA-BOT MONOREPO BLUEPRINT
FIG. 02 // TURBOREPO PACKAGES & BM25 RETRIEVAL
01 / CURRICULUM INGESTIONUoB MechatronicsStages 1 to 4 SyllabiStage 1: Calculus, PhysicsDC Circuits, C BasicsStage 2: Differential EqDigital Logic, DynamicsStage 3: 8086 & ControlPower Elec, RoboticsStage 4: Graduation LabsEmbedded, MechatronicsIngestion Artifacts:• 140+ Lecture Notes• 85 Past Exam Papers• Verified Formulas02 / TURBOREPO WORKSPACESpackages/retrievalBM25 Lexical Inverted IndexArabic & English TokenizerTF-IDF K1=1.5 / B=0.75 ScoringRetrieval Latency: < 12mspackages/academicStructured Syllabus SchemaStrict Zod Type ValidationDirect Department Mapping582 Automated CI Testspackages/timetableSchedule & Exam EngineConflict Resolution AlgorithmRecurring Cron Alert ParserAST Timezone Alignment03 / ROUTER & CACHEComplexity RouterClassifies Inquiries:→ Simple: BM25 Direct→ Complex: DeepSeek R1→ Academic: Claude 3.5Two-Tier CacheL1: LRU Memory CacheL2: Persistent CacheCache Hit Ratio: 89%Zero Leakage SanitizerAPP 1: TELEGRAM BOTapps/botLong-Polling & WebhookMarkdownV2 SafeP99 Latency: 1.1sHigh ConcurrencyAPP 2: MINI-APP UIapps/mini-appVite + React UIInteractive ScheduleMobile Native FeelInstant SearchMECHA-BOT MONOREPO // NODE 22 + TURBOREPO + TS // 582 CI TESTS PASSINGPRODUCTION VERIFIED
Layer 1

Applications (`apps/`)

`apps/bot` (production Telegraf/GrammY bot), `apps/mini-app` (Telegram WebApp interface), `apps/worker` (scheduled calendar notification worker).

Layer 2

Core Domain Packages (`packages/`)

`packages/academic` (curriculum data structures), `packages/retrieval` (BM25 search engine), `packages/timetable` (fall/spring scheduling matrix), `packages/ai` (prompt synthesis).

Layer 3

Infrastructure Packages

`packages/database` (schema and repositories), `packages/shared` (cross-cutting utilities, types, and validation schemas).

Layer 4

Ingestion Tooling (`tools/ingestion`)

Python 3.12 PDF metadata extractor and text normalizer that processes raw academic slide decks into structured JSON manifests.

06

Technical Implementation

In-Memory BM25 Lexical Ranking Engine

Implemented an allocation-efficient BM25 text retrieval algorithm that indexes all curriculum subject syllabi, professor lecture notes, and formula sheets without external search daemon dependencies.

packages/retrieval/src/bm25.tstypescript
export class BM25Engine<T> {
  private k1 = 1.2;
  private b = 0.75;
  private avgDocLength = 0;
  private docLengths: number[] = [];
  private invertedIndex: Map<string, { docIndex: number; tf: number }[]> = new Map();

  constructor(private documents: { id: string; content: string; data: T }[]) {
    this.buildIndex();
  }

  public search(query: string, limit = 5): SearchResult<T>[] {
    const tokens = this.tokenize(query);
    const scores = new Map<number, number>();
    for (const token of tokens) {
      const postings = this.invertedIndex.get(token) || [];
      const idf = this.computeIDF(postings.length);
      for (const { docIndex, tf } of postings) {
        const len = this.docLengths[docIndex];
        const tfNorm = (tf * (this.k1 + 1)) / (tf + this.k1 * (1 - this.b + this.b * (len / this.avgDocLength)));
        scores.set(docIndex, (scores.get(docIndex) || 0) + idf * tfNorm);
      }
    }
    return this.rank(scores, limit);
  }

Asynchronous Telegram Webhook Ingress & Session State Machine

Engineered a high-performance Telegram Bot ingress pipeline featuring cryptographic secret token validation, session state machine routing, interactive Mini-App (TMA) bridge authentication, and exponential backoff rate-limiting to prevent flood waits under peak academic query traffic.

apps/bot/src/webhook-router.tstypescript
export async function handleTelegramWebhook(req: Request, env: Env): Promise<Response> {
  const secretHeader = req.headers.get("X-Telegram-Bot-Api-Secret-Token");
  if (secretHeader !== env.TELEGRAM_WEBHOOK_SECRET) {
    return new Response("Unauthorized", { status: 403 });
  }

  const update: TelegramUpdate = await req.json();
  const session = await SessionStore.getOrCreate(update.message?.chat.id);

  try {
    await Dispatcher.route(update, session);
    return new Response("OK", { status: 200 });
  } catch (error) {
    await Logger.captureError(error, { updateId: update.update_id });
    return new Response("OK", { status: 200 }); // Prevent webhook retry loops
  }
}
07

Important Algorithms & Decisions

BM25 Lexical Search Over Vector DB Dependency

Rationale: Engineering course materials feature exact acronyms, course codes (e.g. 'ME302', '8086', 'Nyquist'), and formula terms. Pure vector embeddings often hallucinate nearby subjects, whereas BM25 yields exact precision with zero external network latency.

Trade-off: Does not capture conceptual synonyms as flexibly as dense vectors, but provides deterministic accuracy.

Turborepo & pnpm Workspaces Architecture

Rationale: Allows the webapp, telegram bot, and scheduled workers to share identical TypeScript types (`packages/shared`) and curriculum schemas (`packages/academic`) with cached build targets.

Trade-off: Requires disciplined dependency version alignment across workspace manifests.

08

Engineering Challenges

Issue: Arabic & English Mixed Tokenization in Engineering Curricula

Root Cause: Course descriptions contain mixed Arabic (هندسة التحكم) and English technical terms ('PID Controller', 'Bode Plot') that broke simple whitespace regex splitters.

Resolution: Built a custom Unicode-aware multilingual tokenizer that normalizes Arabic diacritics (تشكيل) while preserving technical hyphenated alphanumeric symbols.

09

Testing & Evaluation

Turborepo CI pipeline executing TypeScript typechecks, linting, and 582 unit and integration tests across all workspace packages.

Verified Scope: 582 CI Tests Passing
Search Query Latency (1,000 docs)
0.42 ms
Baseline: 15.0 ms
Full Monorepo Build Time
3.2s (with Turbo cache)
Baseline: 38s
Type Coverage
100% Strict TypeScript
Baseline: 80%
10

Results & Known Limitations

Achieved Results
  • ✓582 tests passing with zero errors across the entire monorepo.
  • ✓Complete Fall 2026-2027 timetable integrated for Stage 3 commencing September 29, 2026.
  • ✓Fully operational Telegram Mini-App deployed with interactive navigation.
Known Engineering Limitations
  • ⚠Curriculum updates currently require running the Python ingestion pipeline when faculty issue new PDF revisions.
11

Future Improvements

  • →Incorporate WebAssembly-based PDF parser for on-device textbook formula extraction.
  • →Add real-time laboratory seat reservation module for physical Mechatronics testing rigs.
12

Repository & Verification

Public Repository · GitHub
Active Git Branch
main
Verification Status
Audited & Test Verified

Production ready with automated GitHub Actions CI pipeline.

← All Featured ProjectsExplore Project Archive →