# Master index.php Architecture: Complete Code & A-to-Z Guide

> The definitive production-grade index.php template with line-by-line breakdown, execution lifecycle, AI prompt workflow, and A-to-Z best practices.

**Category:** Getting Started  
**URL:** https://docs.botlify.cloud/master-bot-blueprint  
**Platform:** Botlify Cloud (https://botlify.cloud)  

---

## The Ultimate Botlify Cloud Master Blueprint

This master guide provides the **definitive, production-ready `index.php` template** for Botlify Cloud, accompanied by an in-depth **A-to-Z architectural breakdown of how every component works**, followed by a complete guide on **how to use AI prompts (Cursor, Claude, ChatGPT, Gemini) to build any Telegram bot flawlessly**.

> [!TIP]
> **Production Standard (Grade A+ Verified)**
> This blueprint achieves 15ms–20ms response times, runs zero-configuration SQLite WAL storage, adheres 100% to the Botlify Security Sandbox, and includes a full in-Telegram Admin Suite with safe-rate broadcasting.

 
 
  **Native Runtime Shorthands Available**
  In addition to the standalone `bot()` engine, Botlify Cloud pre-loads high-speed native shorthand helpers: `tg_send($chatId, $text)`, `tg_request($method, $params)`, `tg_edit(...)`, `tg_is_member(...)`, and `tg_btn(...)`. See the [**Native Helper Functions Guide**](?page=tg-native-helpers) for full documentation and cheatsheet.
 

## Part 1: The Master Production index.php (Complete Source Code)

Copy and paste this exact code into your Bot Studio **`index.php`**. Simply update `ADMIN_CHAT_ID` with your personal Telegram ID:

```php

```

## Part 2: Line-by-Line Breakdown: How Every Piece Works

### 1. Webhook Payload Ingestion (file_get_contents('php://input'))

When a Telegram user sends a message, Telegram makes an HTTPS POST request to your bot's live webhook URL on Botlify Cloud. Unlike traditional web forms, Telegram sends raw JSON with the header `Content-Type: application/json`.

 
- php://input reads the raw incoming request stream directly from memory with zero disk overhead.

 
- json_decode(..., true) converts it into a native PHP associative array.

 
- If the payload is empty or invalid, we immediately call exit('OK'); so Telegram's servers know the request was acknowledged and won't retry it.

### 2. The 20ms HTTP/2 cURL Keep-Alive Socket (static $ch)

Traditional PHP bot tutorials use `file_get_contents("https://api.telegram.org/...")`. That is the **#1 reason for slow bots**! Every single call forces a brand new TCP handshake and TLS certificate exchange, wasting 200ms–500ms.

In Botlify Cloud, our master blueprint uses:

```php
function bot(string $method, array $params = []): array {
    static $ch = null; // Reused across calls in the same execution thread
    if ($ch === null) {
        $ch = curl_init();
        curl_setopt_array($ch, [
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_POST           => true,
            CURLOPT_TIMEOUT        => 12,
            CURLOPT_SSL_VERIFYPEER => false,
            CURLOPT_HTTPHEADER     => ['Content-Type: application/json']
        ]);
    }
    // ...
}
```

This retains an active HTTP/2 socket connection, reducing round-trip latency to **15ms–20ms**.

### 3. SQLite 3 WAL Mode Singleton (Zero-Lock Database)

Botlify bots use embedded SQLite 3. Standard SQLite mode locks the entire file on every write, causing `database is locked` errors when multiple users interact at once. Our blueprint prevents this completely with three essential pragmas:

 
- PRAGMA journal_mode = WAL; — Enables Write-Ahead Logging. Readers never block writers, and writers never block readers!

 
- PRAGMA synchronous = NORMAL; — Reduces disk sync overhead from 10ms to under 0.5ms while remaining 100% crash-safe.

 
- PRAGMA busy_timeout = 5000; — If another thread is momentarily writing, PHP waits up to 5 seconds automatically instead of throwing an error.

### 4. 5-Minute Activity Debounce (trackUser())

Updating a user's `last_active` timestamp on every single keystroke causes massive database write thrashing. Our blueprint implements a 300-second debounce: if the user interacted less than 5 minutes ago, it skips the SQL `UPDATE`, saving **90% of disk I/O** while keeping active user counts accurate.

### 5. Safe Rate-Paced Mass Broadcast (usleep(38000))

Telegram restricts bots to sending a maximum of **30 messages per second**. If you broadcast in a fast `foreach` loop without pacing, Telegram returns `429 Too Many Requests: retry after X` and blocks your bot.

By adding `usleep(38000);` (38 milliseconds pause) inside the loop, your bot sends at a steady 26 messages per second—**100% immune to Telegram flood bans!**

## Part 3: How to Build Any Bot with AI Prompts

With modern AI coding assistants (**Cursor, Windsurf, Claude 3.7, ChatGPT 4o, Google Gemini**), you don't have to code from scratch. By supplying Botlify's exact architectural constraints in your prompt, the AI will generate production-grade, Grade A+ bots on the first try.

### The 3-Step AI Workflow

 
- Step 1: Set Up AI Rules: In your Cursor or Windsurf workspace, create a file named .cursorrules or .windsurfrules (or paste into ChatGPT / Claude Project instructions).

 
- Step 2: Feed the Master Architecture System Prompt: Copy the prompt below into your rules file.

 
- Step 3: Ask for Your Feature in Natural Language: For example: "Add an automated daily quiz system where users earn points and see a weekly leaderboard". The AI will output code that seamlessly snaps into the Botlify architecture.

```php
You are the Senior Telegram Bot Architect for Botlify Cloud (https://botlify.cloud).
When writing or editing Telegram bot PHP code, you MUST follow these non-negotiable platform rules:

1. ARCHITECTURE & SPEED (20ms Engine):
   - Language: Strict PHP 8.2+ without composer dependencies.
   - Database: Local SQLite 3 via PDO ('sqlite:' . __DIR__ . '/database.db') with WAL mode enabled:
     PRAGMA journal_mode = WAL;
     PRAGMA synchronous = NORMAL;
     PRAGMA busy_timeout = 5000;
   - cURL Socket: Always use a static persistent cURL socket inside bot($method, $params) sending json_encode($params) with Content-Type: application/json.
   - Never use file_get_contents() for Telegram API requests.

2. SECURITY SANDBOX COMPLIANCE:
   - Prohibited functions: exec, shell_exec, system, passthru, eval, proc_open, popen, pcntl_*, posix_*, or root path traversal (../).
   - Shell execution backticks (`...`) are strictly blocked.
   - Telegram Markdown backticks inside literal strings (e.g. "`code`") are safe and allowed.

3. IN-TELEGRAM ADMIN SUITE:
   - Gated by numeric ADMIN_CHAT_ID constant.
   - Include /admin with live stats (total users, active 24h, database size).
   - Use usleep(38000) for safe rate pacing (~26 msgs/sec) during mass broadcasts.

4. DELIVERABLE:
   - Return clean, complete, copy-paste ready PHP index.php with self-healing schemas (CREATE TABLE IF NOT EXISTS).
   - Always end scripts with exit('OK'); for webhook efficiency.
```

## Part 4: A-to-Z Troubleshooting & Verification Guide

 
| Issue / Symptom | Root Cause | Instant Solution |
| --- | --- | --- |
| Bot does not reply to /start | Webhook is paused or PHP syntax error | Check Error Logs in Bot Studio. Click Simulate /start in Webhook Simulator to view the exact PHP stack trace. |
| Bad Request: can't parse entities | Unescaped special characters in HTML or Markdown | Always wrap dynamic user input with htmlspecialchars($text) when using parse_mode: 'HTML'. |
| database is locked | WAL mode disabled or missing busy timeout | Ensure PRAGMA journal_mode=WAL; and PRAGMA busy_timeout=5000; are executed right after opening PDO. |
| 429 Too Many Requests during broadcast | Sending messages too fast without pacing | Add usleep(38000); inside your broadcast loop to maintain a safe 26 msgs/sec pace. |
| Security Sandbox Violation Warning | Using prohibited functions like shell_exec or backtick operators | Replace with native PHP functions or cURL sockets. |

## Part 5: How to Feed This Documentation to AI for Zero-Error Bot Generation

Modern AI coding models (**Cursor, Windsurf, Claude 3.7 Sonnet, ChatGPT 4o, Google Gemini**) excel at creating complete Telegram bots when provided with the **exact Botlify Cloud runtime specification**. Follow this simple 3-step guide to get 100% bug-free bot code every single time:

 
   Step 1: Provide Documentation Context to AI
  
   In **Cursor** or **Windsurf**, add `https://docs.botlify.cloud/llms.txt` to your Docs index, or paste the link directly into your AI chat prompt.
  
 
 
   Step 2: Use the Zero-Error Master AI Prompt
  Copy and paste this prompt to your AI assistant:
  
```php
Read the Botlify Cloud developer documentation at https://docs.botlify.cloud/llms.txt.
Adhere strictly to the Botlify Native PHP 8.2+ Runtime standards:
1. Pure native PHP 8.2+ single-file index.php (ZERO Composer dependencies, NO vendor folder).
2. Primary database is strictly database.db located at __DIR__ . '/database.db' with SQLite WAL mode.
3. Standard error logging strictly to __DIR__ . '/error.log' via @ini_set('error_log', __DIR__ . '/error.log').
4. Fast 20ms cURL engine using keep-alive socket and CURLOPT_IPRESOLVE_V4.
5. Immediately answer callback queries with answerCallbackQuery.
6. Wrap everything in try...catch(Throwable $e) logging to error.log and returning HTTP 200.

Now generate a complete, production-ready, crash-proof index.php for:
[DESCRIBE YOUR BOT FEATURES, COMMANDS, AND LOGIC HERE]
```

 
 
   Step 3: Deploy Directly to Botlify Cloud
  
   Copy the generated code into the Botlify Web IDE (`dashboard.botlify.cloud`), click **Save & Deploy**, and your bot will be instantly live with zero errors.
