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.
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.
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.
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.
System Architecture
The codebase is divided into independent packages and deployable applications managed via Turborepo.
Applications (`apps/`)
`apps/bot` (production Telegraf/GrammY bot), `apps/mini-app` (Telegram WebApp interface), `apps/worker` (scheduled calendar notification worker).
Core Domain Packages (`packages/`)
`packages/academic` (curriculum data structures), `packages/retrieval` (BM25 search engine), `packages/timetable` (fall/spring scheduling matrix), `packages/ai` (prompt synthesis).
Infrastructure Packages
`packages/database` (schema and repositories), `packages/shared` (cross-cutting utilities, types, and validation schemas).
Ingestion Tooling (`tools/ingestion`)
Python 3.12 PDF metadata extractor and text normalizer that processes raw academic slide decks into structured JSON manifests.
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.
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.
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
}
}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.
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.
Testing & Evaluation
Turborepo CI pipeline executing TypeScript typechecks, linting, and 582 unit and integration tests across all workspace packages.
Results & Known Limitations
- ✓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.
- ⚠Curriculum updates currently require running the Python ingestion pipeline when faculty issue new PDF revisions.
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.
Repository & Verification
Production ready with automated GitHub Actions CI pipeline.