Telegram Learning GatewayProduct overview & engineering case study

Persian learning · PHP / MySQL

A clearer path through Telegram learning.

A privacy-conscious PHP gateway connecting learners to Persian course menus, learning paths and support destinations through authenticated Telegram webhooks.

Self-hosted PHP/MySQL source project. No live Telegram service is operated by this website.

01 / Purpose

One entrance. Several learning destinations.

A learner should not need to know every course bot before choosing a path. The gateway provides a consistent Persian entrance, then hands the journey to independent course and support destinations.

PHP handles the boundary. It authenticates webhook requests, validates the update, resolves an explicit command and loads the corresponding response module. Deep-link parameters take a learner directly to a known menu.

MySQL holds limited state. Chat identifiers, route state, timestamps and update receipts support continuity and replay handling. The gateway routes learners; it does not deliver a full curriculum or generate AI answers.

02 / System architecture

Authenticate. Route. Commit with care.

This is the intended production architecture documented by the source. It does not represent a running service.

Request and reply path · external platform boundaries are labeled
  1. 01 · External

    Learner in Telegram

    A private text message or supported command.

  2. 02 · External

    Telegram Bot API

    Delivers an update to an operator-configured HTTPS endpoint.

  3. 03 · Entry boundary

    Authenticated webhook

    POST, secret-token header, size and JSON validation.

    src/security.php
  4. 04 · Application

    PHP routing logic

    Resolve a known command and its Persian response module.

    src/router.php
  5. 05 · Persistence

    MySQL / InnoDB

    Stage learner state, minimized message metadata and a unique update receipt.

    src/processor.php
  6. 06 · Reply boundary

    Reply or course-bot link

    Attempt the reply via Telegram, then commit only on acknowledgement.

    External destination availability is separate.
The important transaction boundary

Receipt and learner writes remain uncommitted during the reply attempt. A failed delivery rolls them back and returns 503 so Telegram can retry. A committed receipt suppresses a replay. A lost acknowledgement or failed commit can still repeat a reply: this is not exactly-once messaging.

03 / Learning routes

Persian menus, grounded in the source.

The response modules define these paths. The excerpts below are static source examples, not chat messages or an interactive conversation.

Commands resolved by src/router.php
CommandRoleSource module
/startGateway menustart.php
/helpCommand guidancehelp.php
/coursesIndependent course destinationscourses.php
/interviewLearning-path guidanceinterview.php
/support, /contactExternal support destinationsupport.php
From commands/courses.phpRead the source

دوره‌های موجود:

  1. مدیریت محصول دیجیتال
  2. هوش مصنوعی در خدمت مدیران محصول
  3. محصول و کسب‌وکار برای متخصصین منابع انسانی

Direct entry: /start courses, /start interview and /start support resolve known modules. The gateway’s own deep links use the configured, syntax-validated bot username.

Independent destinations: Course and support links are fixed in their source modules. Their ownership, availability and behavior require separate operator review. No active bot link or availability claim is offered here.

04 / Engineering decisions

Small modules. Explicit failure boundaries.

Authenticate before persistence
Production is the default. A missing secret fails closed; the supplied header is checked with hash_equals. Non-POST, unauthenticated, oversized and malformed requests are rejected before a database connection.
Bound the request envelope
Input is capped at 1 MiB; JSON decoding uses depth 32. Text and chat identifiers are validated. Known non-private chats and commands addressed to other bots are ignored. Missing chat type remains accepted for legacy compatibility.
Keep routing inspectable
A fixed command map selects five response modules. Unknown text receives a Persian help hint and preserves an existing route. User text is never interpolated into static Markdown replies.
Make delivery failure visible
Parameterized SQL and InnoDB transactions tie state to unique update receipts. The existing cURL client has 5-second connect and 15-second total timeouts and closes its handle. Transport, HTTP and API failures do not report success; no local retry loop is added.
Inspect the acknowledgement boundary

Excerpt from src/processor.php, after receipt and learner writes:

if ($deliver($message['chat_id'], $reply) !== true) {
    throw new RuntimeException('Telegram delivery was not acknowledged.');
}
$pdo->commit();

The surrounding exception path rolls back an active transaction. This protects local consistency; it cannot undo an already received external reply.

Review the complete processing function

05 / Data lifecycle

Store less. Maintain the lifecycle.

Data minimization is an engineering choice, not anonymity or a privacy certification. Chat IDs, state and metadata may still be sensitive.

Stored by the application

  • Chat identifiers and route state.
  • Creation, update and processing timestamps.
  • Message metadata and unique update receipts.
  • Redacted byte-length text by default: [redacted:bytes=N].

Requires operator maintenance

  • STORE_RAW_MESSAGES=false is the default; new updates do not copy profile names or usernames.
  • MESSAGE_RETENTION_DAYS=30 does not delete anything by itself. Schedule the purge command and monitor its exit status.
  • Chat/state rows and historical profile or raw-message data need separate erasure decisions.
  • Once a receipt expires, replay deduplication no longer covers that update.

The website has no learner records, database connection, cookies, analytics, scripts or Telegram API calls. Its Persian examples come from public source code.

06 / Installation reference

Prepare the source in your own environment.

For future developers choosing to install independently. These instructions do not deploy a service or register a webhook. This mission activates no bot.

Requirements: PHP 8.0–8.4 (64-bit), Composer, Git, cURL, PDO MySQL and an InnoDB MySQL database. A live deployment additionally needs operator-controlled PHP hosting, HTTPS and privately configured Telegram credentials.

git clone https://github.com/AlirezaBelal/telegram-learning-gateway.git
cd telegram-learning-gateway
composer validate --no-check-publish
composer install --no-interaction
Windows · PowerShell

Make PHP and Composer available in your terminal. Check php -v and php -m for the supported runtime, cURL and PDO MySQL.

Copy-Item config/.env.example config/.env
Get-ChildItem tests/*_test.php | ForEach-Object {
    php $_.FullName
    if ($LASTEXITCODE -ne 0) { throw 'Offline test failed' }
}
macOS / Linux · shell

Install a supported PHP runtime and extensions with your platform’s trusted tooling, plus Composer and the MySQL client.

cp config/.env.example config/.env
for test in tests/*_test.php; do
    php "$test" || exit 1
done

These test scripts use synthetic inputs and mocked delivery. The database test explicitly skips without a configured isolated test database. Do not point it at production.

Database initialization & existing-installation migration

For an independently planned fresh installation, bot_database.sql creates aculearn_bot_database and InnoDB tables. Use a separate schema account; never run this as an unreviewed operation against existing data.

# POSIX shell; schema-admin is your separate installation account
mysql -u schema-admin -p < bot_database.sql

# Windows PowerShell equivalent
Get-Content -Raw bot_database.sql | mysql -u schema-admin -p

For an existing installation, back up first and apply migrations/001_update_receipts.sql to the intended database before deploying. Verify users, user_states and messages use InnoDB; plan legacy engine conversions separately. Check existing message indexes before adding the optional retention index. The bootstrap script already includes update receipts.

Secure deployment & retention reference

GitHub Pages serves static files and cannot execute this PHP/MySQL application. Independent operation needs a separate PHP host. Expose only public/, keep config/.env, SQL, scripts, dependencies and logs outside the document root, and disable directory listing and PHP error display.

Privately configure database credentials, TELEGRAM_BOT_TOKEN, a random TELEGRAM_WEBHOOK_SECRET and the actual TELEGRAM_BOT_USERNAME. Runtime SQL privileges are SELECT/INSERT/UPDATE/DELETE; use a different account for schema changes. Keep tested backups and review migrations before release.

Any future webhook registration is a separate operator action over HTTPS using Telegram’s secret_token option. The app checks X-Telegram-Bot-Api-Secret-Token; never put secrets in URLs. No registration command or active endpoint is provided here.

# Inside an independently configured HTTPS Nginx server
root /srv/learning-gateway/public;
client_max_body_size 1m;
location = /index.php {
    include fastcgi_params;
    fastcgi_param SCRIPT_FILENAME $document_root/index.php;
    fastcgi_pass unix:/run/php/php8.3-fpm.sock;
}
location / { return 404; }

Adjust the FPM socket and TLS configuration to the actual host. Do not expose parent directories through aliases. Schedule php scripts/purge_messages.php at least daily in that independently operated environment, protect backups, and monitor failures. No maintenance schedule is activated by this website.

Full deployment and security reference
07 / Maintainability

Test the boundaries without running a bot.

The existing CI matrix covers PHP 8.0, 8.1, 8.2, 8.3 and 8.4 with isolated MySQL 8.0 services. It installs the committed Composer lockfile and validates syntax, routing, authentication, database rollback, redelivery and retention.

  • Offline routing and Persian response modules.
  • Entry-point authentication, JSON shape and request-size rejection.
  • Mocked delivery failure and transaction recovery.
  • Composer validation, dependency audit, token-pattern checks and privacy defaults.
Inspect the actual CI runs
08 / Scope

A gateway source project, with clear limits.

This is a static product presentation and technical case study. No live Telegram bot, webhook, PHP service or database is activated here. No learner data or source credentials are provided. External bots have their own availability and responsibilities. This repository is not an LMS, Telegram client or AI tutor; running it requires independent configuration and deployment.

Authentication and transaction boundaries reduce risk. They do not certify security, erase historical data automatically or guarantee exactly-once delivery.

Built to be understood

Follow the architecture into the source.