# Botlify Cloud Developer Documentation & AI Knowledge Base

> Botlify Cloud (https://botlify.cloud) is an enterprise serverless cloud platform engineered specifically for high-performance PHP 8.2+ Telegram Bots, embedded SQLite databases (WAL mode), Model Context Protocol (AI MCP) server integrations, and developer engineering publications.

## 🤖 MANDATORY AI AGENT DIRECTIVE (ZERO-ERROR BOTLIFY CODE GENERATION)

> **Instructions for AI Models (Cursor, Windsurf, Claude 3.7 Sonnet, ChatGPT 4o, Google Gemini, Copilot, DeepSeek):**
> When asked to create, modify, or troubleshoot a Telegram Bot for Botlify Cloud (`botlify.cloud`), you **MUST STRICTLY COMPLY** with these non-negotiable runtime standards:
>
> 1. **Runtime:** Pure Native PHP 8.2+ only. Single-file `index.php` deployment. **ZERO Composer dependencies** (NO `vendor/autoload.php`, NO `TelegramBot/Api`, NO `GuzzleHttp`). Use native PHP extensions only: `pdo_sqlite`, `curl`, `json`, `mbstring`.
> 2. **Auto-Injected System Credentials (.env):** Never hardcode secrets. Botlify Cloud automatically provisions three locked environment variables:
>    - `BOT_TOKEN`: Active Telegram Bot API token from @BotFather.
>    - `ADMIN_CHAT_ID`: Numeric Telegram User ID of the bot administrator/owner.
>    - `BOT_USERNAME`: Public Telegram username of the bot (without `@`).
>    Always load via native parser:
>    ```php
>    $envFile = __DIR__ . '/.env';
>    $ENV = [];
>    if (is_file($envFile)) {
>        foreach (file($envFile, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES) as $line) {
>            $line = trim($line);
>            if ($line !== '' && $line[0] !== '#' && str_contains($line, '=')) {
>                [$k, $v] = explode('=', $line, 2);
>                $ENV[trim($k)] = trim(trim($v), "'\"");
>            }
>        }
>    }
>    define('BOT_TOKEN', $ENV['BOT_TOKEN'] ?? (getenv('BOT_TOKEN') ?: ''));
>    define('ADMIN_CHAT_ID', (string)($ENV['ADMIN_CHAT_ID'] ?? (getenv('ADMIN_CHAT_ID') ?: '')));
>    define('BOT_USERNAME', (string)($ENV['BOT_USERNAME'] ?? (getenv('BOT_USERNAME') ?: '')));
>    ```
> 3. **Primary Database:** Strictly `database.db` located at `__DIR__ . '/database.db'`. Never use `bot.db` or external databases. Use PDO SQLite with WAL mode (`PRAGMA journal_mode=WAL; PRAGMA synchronous=NORMAL; PRAGMA busy_timeout=5000;`).
> 4. **Self-Healing Column Migrations:** SQLite `CREATE TABLE IF NOT EXISTS` does not update existing tables when adding new columns. Always declare and use `ensureColumn(PDO $pdo, string $table, string $column, string $type = 'TEXT')` for every table column.
> 5. **Error Logging:** Strictly `__DIR__ . '/error.log'`. Put `@ini_set('error_log', __DIR__ . '/error.log');` at the top of `index.php`. Wrap update handling in `try...catch(Throwable $e)` logging to `error.log`.
> 6. **Telegram API Engine:** Use 20ms persistent native cURL (`CURLOPT_IPRESOLVE_V4`, `CURLOPT_TIMEOUT => 15`). Always return `http_response_code(200);` fast.
> 7. **Callback Queries:** Always answer `callback_query` immediately with `answerCallbackQuery` to dismiss the Telegram button loading spinner.
> 8. **HTML Parse Mode:** Always escape dynamic variables with `htmlspecialchars($val, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8')`.
> 9. **Sandbox:** Banned functions (`exec`, `shell_exec`, `system`, `passthru`, `proc_open`, `popen`, `eval`, `assert`, backticks) must never be used.

---

## 🛠️ Botlify Cloud Model Context Protocol (MCP) Server

AI agents can directly connect to Botlify Cloud to manage, deploy, edit, and query bots autonomously via JSON-RPC 2.0 (MCP Spec 2024-11-05).

- **MCP Endpoint:** `https://botlify.cloud/mcp/v1`
- **Authentication:** `Authorization: Bearer <API_KEY>`, `X-API-KEY: <API_KEY>`, or `?token=<YOUR_TOKEN>`
- **Key MCP Tools (41 Tools Total):**
  - `list_bots`: Retrieve list of all hosted bots, status, memory, and webhook URLs (filter by status: `active`, `deleted`, `all`).
  - `create_bot`: Create a new bot instance using a Telegram BotFather token.
  - `delete_bot` / `restore_bot`: Soft delete to recycle bin or restore; pass `permanent=true` to purge completely.
  - `build_and_deploy_bot`: All-in-one syntax validation, file writing to `index.php`, webhook simulation, and status verification.
  - `validate_bot_code`: Dual-engine PHP syntax validator (token parser + linter).
  - `test_bot_webhook`: Simulates an incoming `/start` update and inspects stdout/stderr.
  - `list_files` / `read_file` / `write_file`: Read and write files inside the bot's isolated sandbox.
  - `upload_file`: Upload binary/text files (supports Base64 encoding).
  - `query_database` / `get_database_schema`: Run queries and inspect tables on the bot's local `database.db`.
  - `get_env_variables` / `set_env_variables`: Manage bot environment variables (.env).
  - `create_cron_job` / `list_cron_jobs` / `run_cron_job`: Manage background scheduled workers down to 1-minute intervals.
  - `create_bot_transfer` / `accept_bot_transfer`: Secure bot ownership transfer system.

---

## 🌐 Developer REST API (`api/v1`)

Developers and automated systems can manage bots programmatically using standard HTTP GET/POST requests:

- **Endpoint:** `https://botlify.cloud/api/v1`
- **Authentication Header:** `X-API-KEY: <YOUR_API_KEY>` or `Authorization: Bearer <YOUR_API_KEY>`
- **Standard Actions:**
  - `action=list_bots`: List all bots under the user account (`status=active|deleted|all`).
  - `action=create_bot&token=<BOT_TOKEN>&admin_chat_id=<ID>`: Register a new bot.
  - `action=read_file&bot_id=<ID>&file=index.php`: Fetch `index.php` source.
  - `action=write_file&bot_id=<ID>&file=index.php&content=<PHP_CODE>`: Deploy new code.
  - `action=db_query&bot_id=<ID>&query=<SQL_QUERY>`: Execute SQL on `database.db`.
  - `action=read_file&bot_id=<ID>&file=error.log`: Read latest entries from `error.log`.
  - `action=restart_bot&bot_id=<ID>`: Reset webhooks and clear error flags.
  - `action=webhook_info&bot_id=<ID>`: Query live Telegram `getWebhookInfo` diagnostics.
  - `action=toggle_webhook&bot_id=<ID>&action_type=start|stop|toggle`: Start or pause webhook.
  - `action=build_and_deploy_bot&bot_id=<ID>&code=<PHP_CODE>`: Validate, deploy, and simulate webhook.

---

## 📰 Botlify Cloud Engineering Blog & Technical Publications (Real-Time Live)

> Live articles, architectural deep-dives, developer tutorials, and release notes directly from Botlify Cloud engineers. Automatically refreshed in real-time.
> Blog Home: [https://botlify.cloud/blog/](https://botlify.cloud/blog/) · Total Live Articles: 3

### Categories

- [Guides & Tutorials](https://botlify.cloud/blog/category/guides-tutorials): Step-by-step developer tutorials on building, hosting, and scaling Telegram bots. (1 articles)
- [Telegram Bot API](https://botlify.cloud/blog/category/telegram-bot-api): Deep dives into Telegram Bot API updates, webhooks, inline queries, and mini apps. (1 articles)
- [Bot Architecture & PHP](https://botlify.cloud/blog/category/bot-architecture-php): Best practices for high-performance bot backends, SQLite databases, and security. (1 articles)

### Published Articles

- [How to Host a Telegram Bot 24/7 for Free: Complete Developer Guide (2026)](https://botlify.cloud/blog/how-to-host-telegram-bot-free-24-7) [🔥 Featured]: Learn how to deploy, host, and keep your Telegram bot running 24/7 online for free with automated SSL webhooks, zero-sleep limits, and isolated cloud containers on Botlify.
  - Meta: Category: Guides & Tutorials · 2 min read · Views: 1438 · Published: 2026-10-29
  - Web: https://botlify.cloud/blog/how-to-host-telegram-bot-free-24-7
  - REST API Endpoint: https://botlify.cloud/blog/api.php?action=get_post&slug=how-to-host-telegram-bot-free-24-7

#### Article Full Text: How to Host a Telegram Bot 24/7 for Free: Complete Developer Guide (2026)

# How to Host a Telegram Bot 24/7 for Free: Complete Developer Guide (2026)

Building a Telegram bot is one of the most satisfying developer experiences. Whether you are creating a community management assistant, an automated AI responder, or an e-commerce checkout bot, keeping it **online 24/7 with zero downtime** is the most crucial requirement.

In this guide, you will learn how modern cloud platforms like **Botlify Cloud** allow you to deploy, monitor, and host Telegram bots completely free with automatic SSL webhooks, zero sleep limits, and isolated containers.

> [!TIP]
> Traditional VPS servers often require manual Nginx configuration, SSL certbot renewal scripts, and systemd daemons. Botlify handles all of this automatically in under 60 seconds.

---

## 1. Getting Your Telegram Bot Token

Before setting up hosting, create your bot using Telegram's official `@BotFather`:

1. Open Telegram and search for `@BotFather`.
2. Send the command `/newbot`.
3. Choose a friendly display name (e.g., `My Awesome Bot`).
4. Choose a unique username ending in `bot` (e.g., `MySuperHelper_bot`).
5. Copy your **HTTP API Token** safely. It will look like:
   `1234567890:ABCdefGhIJKlmNoPQRsTUVwxyZ`

> [!WARNING]
> Never share your Telegram bot token or commit it to public GitHub repositories! Anyone with your token can control your bot.

---

## 2. Webhooks vs Long Polling: Why Webhooks Win

When hosting Telegram bots, developers choose between two modes:

| Mode | Mechanism | Server Resource | Best Use Case |
| :--- | :--- | :--- | :--- |
| **Long Polling** | Bot continuously queries `getUpdates` | High CPU & Constant RAM | Local testing & dev |
| **Webhooks** | Telegram pushes JSON to your HTTPS URL | Ultra-low CPU (On-demand) | 24/7 Production Hosting |

With webhooks, your server only wakes up when a user sends a message. This makes webhooks **10x more energy-efficient** and capable of handling traffic spikes effortlessly.

---

## 3. Writing Your Webhook Script in PHP

Here is a clean, production-ready PHP webhook template:

```php
<?php
declare(strict_types=1);

// Receive incoming JSON update from Telegram
$rawInput = file_get_contents('php://input');
if (empty($rawInput)) {
    http_response_code(200);
    echo "Botlify Bot Webhook Active!";
    exit;
}

$update = json_decode($rawInput, true);
$message = $update['message'] ?? null;

if (!$message) {
    http_response_code(200);
    exit;
}

$chatId = $message['chat']['id'];
$text   = trim($message['text'] ?? '');
$botToken = getenv('BOT_TOKEN') ?: 'YOUR_BOT_TOKEN_HERE';

if ($text === '/start') {
    $reply = "👋 Hello! I am running 24/7 on Botlify Cloud with 0% downtime!";
    sendTelegramMessage($botToken, $chatId, $reply);
}

function sendTelegramMessage(string $token, int $chatId, string $text): void
{
    $url = "https://api.telegram.org/bot{$token}/sendMessage";
    $payload = [
        'chat_id' => $chatId,
        'text' => $text,
        'parse_mode' => 'HTML',
    ];
    
    $ch = curl_init($url);
    curl_setopt_array($ch, [
        CURLOPT_POST => true,
        CURLOPT_POSTFIELDS => http_build_query($payload),
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_TIMEOUT => 5,
    ]);
    curl_exec($ch);
    curl_close($ch);
}
```

---

## 4. Deploying to Botlify Cloud in 1-Click

Deploying your bot on **Botlify** requires zero command-line configuration:

1. Navigate to **[Botlify Dashboard](https://botlify.cloud/login.php)**.
2. Click **Create New Bot** and paste your BotFather API Token.
3. Botlify automatically sets the webhook via Telegram API with high-grade SSL certificates.
4. Upload your `bot.php` or edit code right inside the **Web IDE**.
5. Your bot is live immediately and backed by persistent isolated storage.

### Key Benefits of Botlify Free Tier:
- **100% Free**: No credit card required.
- **Isolated Sandbox**: Safe, containerized execution environment.
- **Embedded Database**: Local `database.db` SQLite storage included out of the box.
- **Auto SSL Webhook**: Instant Cloudflare & Let's Encrypt certificates.

---

## Summary

Hosting a 24/7 Telegram bot no longer requires expensive VPS subscriptions or complex Linux administration. With webhooks and Botlify Cloud, you can launch scalable, zero-downtime bots in seconds.

Happy Bot Building!

- [Building High-Concurrency Telegram Webhooks with PHP: Architecture Deep Dive](https://botlify.cloud/blog/building-high-concurrency-telegram-webhooks-php) [🔥 Featured]: Explore how to optimize PHP webhooks for sub-50ms execution times, fastcgi_finish_request, secret token verification, and persistent cURL connection pooling.
  - Meta: Category: Telegram Bot API · 2 min read · Views: 917 · Published: 2026-10-29
  - Web: https://botlify.cloud/blog/building-high-concurrency-telegram-webhooks-php
  - REST API Endpoint: https://botlify.cloud/blog/api.php?action=get_post&slug=building-high-concurrency-telegram-webhooks-php

#### Article Full Text: Building High-Concurrency Telegram Webhooks with PHP: Architecture Deep Dive

# Building High-Concurrency Telegram Webhooks with PHP: Architecture Deep Dive

When your Telegram bot grows from a few hundred users to hundreds of thousands of daily interactions, traditional synchronous webhook handling starts to crack. Users experience delayed message delivery, timeouts appear in the Telegram Webhook Info, and your server CPU spikes.

In this architectural deep dive, we explore how to optimize your PHP webhooks for sub-50ms execution times and massive concurrency.

> [!NOTE]
> Telegram's webhook timeout limit is **60 seconds**, but if your script takes more than 3-5 seconds to return HTTP 200, Telegram will begin retrying the update, causing duplicate responses.

---

## The Rule of Fast Webhooks: Acknowledge First

The golden rule of high-scale Telegram webhooks is:
**Acknowledge Telegram with HTTP 200 OK as fast as possible.**

Do not perform heavy operations (such as generating AI completions, sending multi-recipient broadcasts, or downloading 20MB voice files) directly inside the incoming HTTP thread.

### The Fast-Response Architecture

```
User Message
     │
     ▼
Telegram API Server
     │ (HTTPS POST)
     ▼
[Botlify Webhook Gateway] ────▶ [Fast HTTP 200 OK + Connection Close]
     │
     ▼
[Async Background Task / Queue]
     │
     ▼
[Bot Business Logic & Telegram API Reply]
```

---

## Technique 1: Utilizing FastCGI `fastcgi_finish_request()`

If your PHP server runs PHP-FPM (like Botlify's container infrastructure), you can instantly flush the HTTP 200 status back to Telegram and continue processing in the background:

```php
<?php
// Receive payload
$input = file_get_contents('php://input');
$update = json_decode($input, true);

// Send HTTP 200 OK immediately to release Telegram connection
http_response_code(200);
echo json_encode(['ok' => true]);

if (function_exists('fastcgi_finish_request')) {
    fastcgi_finish_request(); // Telegram receives response immediately!
}

// Now you can safely run longer background operations:
processHeavyBotLogic($update);
```

---

## Technique 2: Webhook Secret Token Verification

In Telegram Bot API 6.1+, you can set a secret token via `setWebhook`:

```bash
curl -F "url=https://botlify.cloud/webhook.php" \
     -F "secret_token=my_super_secret_token_abc123" \
     https://api.telegram.org/bot<TOKEN>/setWebhook
```

In your PHP webhook, verify this token instantly before doing anything else:

```php
$secret = $_SERVER['HTTP_X_TELEGRAM_BOT_API_SECRET_TOKEN'] ?? '';
if ($secret !== 'my_super_secret_token_abc123') {
    http_response_code(403);
    exit('Unauthorized access.');
}
```

This prevents unauthorized third-party requests and bots from hitting your backend endpoints.

---

## Technique 3: Connection Reuse with cURL Keep-Alive

Making a new TLS connection to `api.telegram.org` for every single message consumes 100-200ms in SSL handshake overhead. Reusing your cURL handle or using persistent HTTP connections speeds up message delivery by **400%**:

```php
function telegram_request(string $method, array $params = []): array
{
    static $ch = null;
    $token = getenv('BOT_TOKEN');
    $url = "https://api.telegram.org/bot{$token}/{$method}";

    if ($ch === null) {
        $ch = curl_init();
        curl_setopt_array($ch, [
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_POST => true,
            CURLOPT_TIMEOUT => 10,
            CURLOPT_TCP_KEEPALIVE => 1,
            CURLOPT_HTTPHEADER => ['Content-Type: application/json'],
        ]);
    }

    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($params));
    
    $res = curl_exec($ch);
    return json_decode((string)$res, true) ?: [];
}
```

---

## Conclusion

By adopting `fastcgi_finish_request()`, verifying secret tokens, and reusing persistent cURL connections, your PHP Telegram bots can comfortably handle thousands of concurrent requests with rock-solid stability.

- [Telegram Bot Security: Protecting Bot Tokens, Webhooks, and Secrets in Production](https://botlify.cloud/blog/telegram-bot-security-tokens-webhooks-secrets): Security best practices for Telegram bots: protecting tokens from git leaks, numerical chat ID authentication, SQL injection defense, and rate limiting.
  - Meta: Category: Bot Architecture & PHP · 3 min read · Views: 651 · Published: 2026-10-29
  - Web: https://botlify.cloud/blog/telegram-bot-security-tokens-webhooks-secrets
  - REST API Endpoint: https://botlify.cloud/blog/api.php?action=get_post&slug=telegram-bot-security-tokens-webhooks-secrets

#### Article Full Text: Telegram Bot Security: Protecting Bot Tokens, Webhooks, and Secrets in Production

# Telegram Bot Security: Protecting Bot Tokens, Webhooks, and Secrets in Production

Security is often overlooked when developing Telegram bots—until a token gets leaked, a bot gets hijacked, or someone abuses an unauthenticated webhook.

In this article, we cover the top security best practices every Telegram bot engineer must implement before launching to production.

---

## 1. Never Hardcode Bot Tokens in Source Code

Hardcoding tokens directly into `bot.php` is the #1 reason bots get compromised. Use environment variables or protected configuration files:

```php
// Bad:
$botToken = '719283749:AAFkj4829ksj-dklasjd';

// Good:
$botToken = getenv('BOT_TOKEN');
if (!$botToken) {
    throw new RuntimeException("BOT_TOKEN environment variable is not configured.");
}
```

Botlify provides an integrated **Environment Variable Manager** in the dashboard where you can securely store `BOT_TOKEN`, `ADMIN_CHAT_ID`, and database credentials without ever exposing them to git repositories.

---

## 2. Restrict Sensitive Commands to Admin Chat IDs

Admin commands such as `/broadcast`, `/stats`, `/ban`, or `/restart` must always verify the sender's Telegram `chat_id`:

```php
$adminChatId = (int)getenv('ADMIN_CHAT_ID');
$senderChatId = (int)($message['chat']['id'] ?? 0);

if ($senderChatId !== $adminChatId) {
    // Silently ignore or deny
    exit;
}

// Proceed with admin privileged action
```

> [!CAUTION]
> Never authenticate admins based solely on `username` (e.g. `@johndoe`) because usernames can be changed or impersonated. Telegram's numerical `id` is permanent and immutable.

---

## 3. SQL Injection Prevention in Bot Databases

If your bot stores user states, points, or messages in SQLite or MySQL, always use prepared statements:

```php
// Vulnerable to SQL injection:
// $db->query("SELECT * FROM users WHERE chat_id = " . $chatId);

// Secure with Prepared Statement:
$stmt = $db->prepare("SELECT * FROM users WHERE chat_id = ?");
$stmt->execute([$chatId]);
$user = $stmt->fetch();
```

---

## 4. Rate Limiting Bot Users

Spam attacks from malicious users can flood your bot and hit Telegram's global 30-message-per-second limit. Implement a simple rate limiter in memory or SQLite:

```php
function is_rate_limited(PDO $db, int $chatId, int $maxPerMinute = 20): bool
{
    $now = time();
    $minuteAgo = $now - 60;
    
    // Clean old logs
    $db->prepare("DELETE FROM user_rate_limits WHERE timestamp < ?")->execute([$minuteAgo]);
    
    // Count recent
    $st = $db->prepare("SELECT COUNT(*) FROM user_rate_limits WHERE chat_id = ?");
    $st->execute([$chatId]);
    $count = (int)$st->fetchColumn();
    
    if ($count >= $maxPerMinute) {
        return true;
    }
    
    $ins = $db->prepare("INSERT INTO user_rate_limits (chat_id, timestamp) VALUES (?, ?)");
    $ins->execute([$chatId, $now]);
    return false;
}
```

---

## Summary

Securing your bot requires minimal effort but protects you and your community from devastating leaks. Store tokens in environment variables, verify numerical chat IDs, use prepared queries, and configure webhook secrets.


---

## ⚡ Botlify Blog REST API (`blog/api.php`)

AI agents, mobile apps, and headless clients can query and syndicate Botlify blog content via JSON REST API:

- **Base Endpoint:** `https://botlify.cloud/blog/api.php`
- **Public Query Actions:**
  - `action=get_posts`: Retrieve paginated posts (Query params: `page=1`, `limit=10`, `category={slug}`, `tag={slug}`, `search={query}`, `sort=latest|popular`).
  - `action=get_post&slug={slug}`: Retrieve full post details, parsed HTML, TOC headings, and related posts.
  - `action=get_categories`: List all categories with post counts.
  - `action=get_tags`: List all tags with usage counts.
  - `action=get_stats`: Get total post count, categories, tags, and total views.
- **Authenticated Management Actions (Requires `X-API-KEY` or `Authorization: Bearer`):**
  - `POST action=create_post`: Publish new article (JSON body with `title`, `content`, `excerpt`, `category_id`, `tags`, `meta_title`, `meta_description`).
  - `POST action=update_post&id={id}`: Update an existing article.
  - `POST action=delete_post&id={id}`: Permanently delete an article.
  - `POST action=upload_image`: Upload cover images and inline assets to `/blog/uploads/`.

---


# Botlify Cloud — Master Production Developer Documentation & Enterprise Knowledge Base

> The definitive, full-text developer documentation for Botlify Cloud (https://botlify.cloud).
> Covers high-performance serverless PHP 8.2+ Telegram bots, embedded SQLite 3 WAL databases, Model Context Protocol (AI MCP) server tooling, Developer REST APIs, Broadcast Ad Network, Engineering Blog System, and GitHub Automated Cloud Backups.
> Platform: Botlify Cloud (https://botlify.cloud) · Documentation Hub: https://docs.botlify.cloud
> Last Updated: 2026-10-30 01:37:06 UTC

---

## 📑 Master Table of Contents

1. [Platform Overview & Serverless Architecture](#1-platform-overview--serverless-architecture)
2. [🤖 Mandatory AI Agent Directives & Zero-Error Botlify Standard](#2--mandatory-ai-agent-directives--zero-error-botlify-standard)
3. [📋 Canonical Zero-Error Master index.php Production Blueprint](#3--canonical-zero-error-master-indexphp-production-blueprint)
4. [📖 Master Guide: Telegram Bot Making on Botlify Cloud (All 50 Production Topics & Boilerplates)](#4--master-guide-telegram-bot-making-on-botlify-cloud)
5. [🛠️ Botlify Model Context Protocol (MCP) Server & 37 Tools Specification](#5-botlify-model-context-protocol-mcp-server)
6. [🌐 Developer REST API (user_api.php) Reference](#6-developer-rest-api-user_apiphp-reference)
7. [📢 Telegram Broadcast Ads & Analytics API (broadcast_api.php)](#7-telegram-broadcast-ads--analytics-api)
8. [📰 Botlify Engineering Blog Engine & Blog REST API (blog/api.php)](#8-botlify-engineering-blog-engine--blog-rest-api)
9. [📦 GitHub Automated Cloud Backup Engine (includes/github_backup.php)](#9-github-automated-cloud-backup-engine)
10. [🤖 Real-Time Dynamic LLMs.txt & AI Context Discovery (llms.php)](#10-real-time-dynamic-llmstxt--ai-context-discovery)
11. [🗺️ Dynamic Real-Time XML Sitemaps & Discovery (sitemap.php)](#11-dynamic-real-time-xml-sitemaps--discovery)
12. [⚡ Complete Telegram Bot API Methods Reference (A-Z, 203 Methods)](#12-complete-telegram-bot-api-methods-reference)
13. [🧩 Complete Telegram Bot API Types Reference (A-Z, 401 Types)](#13-complete-telegram-bot-api-types-reference)
14. [📚 Platform Developer Guides & Studio Manuals (34 In-Depth Guides)](#14--platform-developer-guides--studio-manuals-34-in-depth-guides)

---

## 1. Platform Overview & Serverless Architecture

Botlify Cloud (`botlify.cloud`) is a specialized high-performance cloud hosting platform and developer ecosystem engineered specifically for serverless Telegram Bots, embedded SQLite databases, Model Context Protocol (AI MCP) servers, and developer blogging.

### Core Architectural Pillars

- **Pure Native PHP 8.2+ Runtime:** Single-file `index.php` execution model with pre-warmed OPcache and persistent sockets. Zero external Composer dependencies to eliminate cold-start penalties and security vulnerabilities.
- **Embedded SQLite 3 with Write-Ahead Logging (WAL Mode):** Every bot runs an isolated SQLite database at `database.db` with 32MB RAM caching (`PRAGMA journal_mode = WAL; PRAGMA synchronous = NORMAL; PRAGMA busy_timeout = 5000;`). Eliminates remote TCP handshake latency for sub-millisecond query execution.
- **Ultra-Fast 20ms Telegram API Engine:** Persistent native cURL socket with IPv4 resolution (`CURLOPT_IPRESOLVE_V4`), TCP No-Delay, and HTTP/2 multiplexing.
- **Dedicated NVMe SSD Sandboxing:** Every bot is provisioned an isolated workspace under `storage/users/{chat_id}/bots/{bot_username}/` with automatic `.env` credential management and strict execution sandboxing.
- **Model Context Protocol (MCP):** Native JSON-RPC 2.0 / SSE endpoint at `https://botlify.cloud/mcp.php` allowing Cursor, Windsurf, Claude, and Gemini to autonomously build, validate, query, and deploy bots.
- **Automated GitHub Cloud Backup:** Automatic cron-driven synchronization of MySQL database dumps (`database.sql`) and critical platform directories (`assets`, `blog`, `storage`, `recycle`, `ad_delete`) to private GitHub repositories with self-healing Git lock recovery.
- **Real-Time Dynamic LLMs & Sitemaps:** Compliant with https://llmstxt.org, dynamically serving live blog articles, MCP tools, and SEO feeds to AI crawlers with conditional HTTP 304 caching.

---

## 2. 🤖 Mandatory AI Agent Directives & Zero-Error Botlify Standard

> **Instructions for AI Models (Cursor, Windsurf, Claude 3.7 Sonnet, ChatGPT 4o, Google Gemini, Copilot, DeepSeek):**
> When asked to create, modify, or troubleshoot a Telegram Bot for Botlify Cloud (`botlify.cloud`), you **MUST STRICTLY COMPLY** with these non-negotiable runtime standards:
>
> 1. **Runtime:** Pure Native PHP 8.2+ only. Single-file `index.php` deployment. **ZERO Composer dependencies** (NO `vendor/autoload.php`, NO `TelegramBot/Api`, NO `GuzzleHttp`). Use native PHP extensions only: `pdo_sqlite`, `curl`, `json`, `mbstring`.
> 2. **Auto-Injected System Credentials (.env):** Never hardcode secrets. Botlify Cloud automatically provisions three locked environment variables:
>    - `BOT_TOKEN`: Active Telegram Bot API token from @BotFather.
>    - `ADMIN_CHAT_ID`: Numeric Telegram User ID of the bot administrator/owner.
>    - `BOT_USERNAME`: Public Telegram username of the bot (without `@`).
>    Always load via native parser:
>    ```php
>    $envFile = __DIR__ . '/.env';
>    $ENV = [];
>    if (is_file($envFile)) {
>        foreach (file($envFile, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES) as $line) {
>            $line = trim($line);
>            if ($line !== '' && $line[0] !== '#' && str_contains($line, '=')) {
>                [$k, $v] = explode('=', $line, 2);
>                $ENV[trim($k)] = trim(trim($v), "'\\"");
>            }
>        }
>    }
>    define('BOT_TOKEN', $ENV['BOT_TOKEN'] ?? (getenv('BOT_TOKEN') ?: ''));
>    define('ADMIN_CHAT_ID', (string)($ENV['ADMIN_CHAT_ID'] ?? (getenv('ADMIN_CHAT_ID') ?: '')));
>    define('BOT_USERNAME', (string)($ENV['BOT_USERNAME'] ?? (getenv('BOT_USERNAME') ?: '')));
>    ```
> 3. **Primary Database:** Strictly `database.db` located at `__DIR__ . '/database.db'`. Never use `bot.db` or external databases. Use PDO SQLite with WAL mode (`PRAGMA journal_mode=WAL; PRAGMA synchronous=NORMAL; PRAGMA busy_timeout=5000;`).
> 4. **Self-Healing Column Migrations:** SQLite `CREATE TABLE IF NOT EXISTS` does not update existing tables when adding new columns. Always declare and use `ensureColumn(PDO $pdo, string $table, string $column, string $type = 'TEXT')` for every table column.
> 5. **Error Logging:** Strictly `__DIR__ . '/error.log'`. Put `@ini_set('error_log', __DIR__ . '/error.log');` at the top of `index.php`. Wrap update handling in `try...catch(Throwable $e)` logging to `error.log`.
> 6. **Telegram API Engine:** Use 20ms persistent native cURL (`CURLOPT_IPRESOLVE_V4`, `CURLOPT_TIMEOUT => 15`). Always return `http_response_code(200);` fast.
> 7. **Callback Queries:** Always answer `callback_query` immediately with `answerCallbackQuery` to dismiss the Telegram button loading spinner.
> 8. **HTML Parse Mode:** Always escape dynamic variables with `htmlspecialchars($val, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8')`.
> 9. **Sandbox:** Banned functions (`exec`, `shell_exec`, `system`, `passthru`, `proc_open`, `popen`, `eval`, `assert`, backticks) must never be used.

---

## 3. 📋 Canonical Zero-Error Master index.php Production Blueprint

Every Telegram Bot generated for Botlify Cloud MUST follow this production structure:

```php
<?php
declare(strict_types=1);

/**
 * ══════════════════════════════════════════════════════════════════════════════
 * Botlify Cloud — Master Production Telegram Bot Engine
 * Version: 4.0 (Official Native Runtime Standard, Complete FSM & Admin Suite)
 *
 * Designed exclusively for the Botlify Cloud Serverless PHP 8.2+ Runtime.
 * Features:
 *   • Auto-loads credentials from Botlify .env file (BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME)
 *   • Direct SQLite 3 (database.db) with WAL mode & 32MB RAM caching
 *   • Self-Healing Database Migrations (ensureColumn) preventing crashes on update
 *   • In-Database Finite State Machine (FSM) with /cancel support
 *   • Full In-Telegram Interactive /admin Panel with Live Stats & copyMessage Broadcast
 *   • 20ms High-speed persistent cURL HTTP/2 socket (bot() helper)
 *   • Strict Error Logging to __DIR__ . '/error.log'
 *   • Immediate callback query answer to dismiss button loading spinners
 * ══════════════════════════════════════════════════════════════════════════════
 */

// ── 0. ERROR LOGGING & PLATFORM RUNTIME CONFIG ───────────────────────────────
@ini_set('log_errors', '1');
@ini_set('error_log', __DIR__ . '/error.log');
@ini_set('display_errors', '0');

// ── 1. CREDENTIALS & ENVIRONMENT AUTO-LOADER ────────────────────────────────
$envFile = __DIR__ . '/.env';
$ENV = [];
if (is_file($envFile)) {
    foreach (file($envFile, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES) as $line) {
        $line = trim($line);
        if ($line !== '' && $line[0] !== '#' && str_contains($line, '=')) {
            [$k, $v] = explode('=', $line, 2);
            $ENV[trim($k)] = trim(trim($v), "'\"");
        }
    }
}

// Bot credentials (auto-injected by Botlify Cloud in .env)
define('BOT_TOKEN', $ENV['BOT_TOKEN'] ?? (getenv('BOT_TOKEN') ?: ''));
define('ADMIN_CHAT_ID', (string)($ENV['ADMIN_CHAT_ID'] ?? (getenv('ADMIN_CHAT_ID') ?: '')));
define('BOT_USERNAME', (string)($ENV['BOT_USERNAME'] ?? (getenv('BOT_USERNAME') ?: '')));
define('DB_FILE', __DIR__ . '/database.db');

// CLI or Health Check Guard
if (BOT_TOKEN === '') {
    if (php_sapi_name() === 'cli' || empty($_SERVER['REQUEST_METHOD'])) {
        echo "Botlify Bot Engine loaded. Please configure BOT_TOKEN in .env or Botlify Studio.\n";
    }
    exit;
}

// ── 2. DATABASE: HIGH-CONCURRENCY SQLITE WAL & SELF-HEALING ENGINE ───────────
function db(): PDO {
    static $pdo = null;
    if ($pdo === null) {
        $pdo = new PDO('sqlite:' . DB_FILE, null, null, [
            PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
            PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
            PDO::ATTR_TIMEOUT            => 5
        ]);

        // Production-tuned SQLite Pragmas for maximum concurrency
        $pdo->exec('PRAGMA journal_mode = WAL;');
        $pdo->exec('PRAGMA synchronous = NORMAL;');
        $pdo->exec('PRAGMA busy_timeout = 5000;');
        $pdo->exec('PRAGMA temp_store = MEMORY;');
        $pdo->exec('PRAGMA cache_size = -32000;');
        $pdo->exec('PRAGMA mmap_size = 268435456;');
        $pdo->exec('PRAGMA cache_size = -32000;'); // 32MB RAM Cache
        $pdo->exec('PRAGMA temp_store = MEMORY;');

        // Initialize Core Schema
        $pdo->exec('CREATE TABLE IF NOT EXISTS users (
            user_id INTEGER PRIMARY KEY,
            username TEXT,
            first_name TEXT,
            is_banned INTEGER DEFAULT 0,
            ban_reason TEXT,
            created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
            last_active DATETIME DEFAULT CURRENT_TIMESTAMP
        );');

        $pdo->exec('CREATE TABLE IF NOT EXISTS user_states (
            chat_id TEXT PRIMARY KEY,
            state TEXT NOT NULL,
            state_data TEXT,
            updated_at INTEGER NOT NULL
        );');

        $pdo->exec('CREATE TABLE IF NOT EXISTS broadcast_logs (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            admin_id TEXT NOT NULL,
            sent_count INTEGER NOT NULL,
            failed_count INTEGER NOT NULL,
            message_text TEXT,
            created_at DATETIME DEFAULT CURRENT_TIMESTAMP
        );');

        // Self-Healing Column Migrations: ensures columns exist even on old databases
        ensureColumn($pdo, 'users', 'is_banned', 'INTEGER DEFAULT 0');
        ensureColumn($pdo, 'users', 'ban_reason', 'TEXT');
        ensureColumn($pdo, 'users', 'last_active', 'DATETIME');
    }
    return $pdo;
}

function ensureColumn(PDO $pdo, string $table, string $column, string $type = 'TEXT'): void {
    try {
        $cols = $pdo->query("PRAGMA table_info({$table})")->fetchAll(PDO::FETCH_COLUMN, 1);
        if (!in_array($column, $cols, true)) {
            $pdo->exec("ALTER TABLE {$table} ADD COLUMN {$column} {$type}");
        }
    } catch (Throwable $e) {}
}

// ── 3. FINITE STATE MACHINE (FSM) HELPERS ────────────────────────────────────
function getState(int|string $chatId): array {
    $st = db()->prepare("SELECT state, state_data FROM user_states WHERE chat_id = ? LIMIT 1");
    $st->execute([(string)$chatId]);
    $row = $st->fetch();
    if ($row) {
        return ['state' => (string)$row['state'], 'data' => json_decode((string)$row['state_data'], true) ?: []];
    }
    return ['state' => '', 'data' => []];
}

function setState(int|string $chatId, string $state, array $data = []): void {
    $st = db()->prepare("INSERT INTO user_states (chat_id, state, state_data, updated_at) VALUES (?, ?, ?, ?)
        ON CONFLICT(chat_id) DO UPDATE SET state = excluded.state, state_data = excluded.state_data, updated_at = excluded.updated_at");
    $st->execute([(string)$chatId, $state, json_encode($data), time()]);
}

function clearState(int|string $chatId): void {
    $st = db()->prepare("DELETE FROM user_states WHERE chat_id = ?");
    $st->execute([(string)$chatId]);
}

// ── 4. TELEGRAM API ENGINE: 20ms PERSISTENT cURL ─────────────────────────────
function bot(string $method, array $params = []): array {
    if (!defined('BOT_TOKEN') || BOT_TOKEN === '') {
        return ['ok' => false];
    }
    static $ch = null;
    if ($ch === null || !($ch instanceof \CurlHandle || is_resource($ch))) {
        $ch = curl_init();
    }
    $opts = [
        CURLOPT_URL               => 'https://api.telegram.org/bot' . BOT_TOKEN . '/' . $method,
        CURLOPT_RETURNTRANSFER    => true,
        CURLOPT_POST              => true,
        CURLOPT_POSTFIELDS        => json_encode($params, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES),
        CURLOPT_HTTPHEADER        => ['Content-Type: application/json; charset=utf-8'],
        CURLOPT_CONNECTTIMEOUT    => 8,
        CURLOPT_TIMEOUT           => 15,
        CURLOPT_IPRESOLVE         => CURL_IPRESOLVE_V4,
        CURLOPT_TCP_NODELAY       => true,
        CURLOPT_DNS_CACHE_TIMEOUT => 3600,
        CURLOPT_SSL_VERIFYPEER    => false,
        CURLOPT_SSL_VERIFYHOST    => false
    ];
    if (defined('CURL_HTTP_VERSION_2TLS')) {
        $opts[CURLOPT_HTTP_VERSION] = CURL_HTTP_VERSION_2TLS;
    }
    curl_setopt_array($ch, $opts);
    $res = curl_exec($ch);
    return json_decode((string)$res, true) ?: ['ok' => false];
}

// ── 5. UTILITY & SECURITY HELPERS ───────────────────────────────────────────
function clean(string $text): string {
    return htmlspecialchars($text, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
}

function isAdmin(int|string $userId): bool {
    return ADMIN_CHAT_ID !== '' && (string)$userId === (string)ADMIN_CHAT_ID;
}

function getAdminDashboardMarkup(): array {
    return [
        'inline_keyboard' => [
            [
                ['text' => '📊 Live Analytics', 'callback_data' => 'admin_stats', 'style' => 'primary'],
                ['text' => '📢 Mass Broadcast', 'callback_data' => 'admin_broadcast', 'style' => 'success']
            ],
            [
                ['text' => '👥 User Management', 'callback_data' => 'admin_users'],
                ['text' => '🧹 Clear Error Log', 'callback_data' => 'admin_clear_logs']
            ],
            [
                ['text' => '❌ Close Admin Panel', 'callback_data' => 'admin_close', 'style' => 'danger']
            ]
        ]
    ];
}

function registerOrUpdateUser(int $userId, string $username, string $firstName): array {
    $db = db();
    try {
        $stmt = $db->prepare('INSERT INTO users (user_id, username, first_name) VALUES (?, ?, ?)
            ON CONFLICT(user_id) DO UPDATE SET
                username = excluded.username,
                first_name = excluded.first_name,
                last_active = CURRENT_TIMESTAMP');
        $stmt->execute([$userId, $username, $firstName]);
    } catch (Throwable $e) {
        $stmt = $db->prepare('INSERT OR IGNORE INTO users (user_id, username, first_name) VALUES (?, ?, ?)');
        $stmt->execute([$userId, $username, $firstName]);
    }

    $st = $db->prepare('SELECT * FROM users WHERE user_id = ? LIMIT 1');
    $st->execute([$userId]);
    return $st->fetch() ?: [];
}

// ── 6. MAIN WEBHOOK DISPATCHER ───────────────────────────────────────────────
try {
    $raw = file_get_contents('php://input');
    if (!$raw && isset($GLOBALS['FBH_RAW_INPUT'])) {
        $raw = $GLOBALS['FBH_RAW_INPUT'];
    }
    $update = json_decode((string)$raw, true);

    if (!is_array($update)) {
        http_response_code(200);
        exit('OK');
    }

    // A. Handle Callback Queries (Inline Keyboard Buttons)
    if (isset($update['callback_query'])) {
        $cb        = $update['callback_query'];
        $cbId      = (string)$cb['id'];
        $chatId    = $cb['message']['chat']['id'] ?? 0;
        $messageId = $cb['message']['message_id'] ?? 0;
        $cbUserId  = (int)($cb['from']['id'] ?? 0);
        $data      = (string)($cb['data'] ?? '');

        // Immediately dismiss the loading spinner on user's Telegram client
        bot('answerCallbackQuery', ['callback_query_id' => $cbId]);

        // ── Admin-Only Callback Suite ──
        if (str_starts_with($data, 'admin_')) {
            if (!isAdmin($cbUserId)) {
                bot('answerCallbackQuery', [
                    'callback_query_id' => $cbId,
                    'text'              => '⛔ Unauthorized: Restricted to bot administrator.',
                    'show_alert'        => true
                ]);
                http_response_code(200);
                exit('OK');
            }

            if ($data === 'admin_home') {
                clearState($chatId);
                $totalUsers = (int)db()->query('SELECT COUNT(*) FROM users')->fetchColumn();
                $dbSize = is_file(DB_FILE) ? round(filesize(DB_FILE) / 1024, 2) : 0;
                bot('editMessageText', [
                    'chat_id'      => $chatId,
                    'message_id'   => $messageId,
                    'text'         => "👑 <b>Bot Admin Control Suite</b>\n\n• <b>Total Users:</b> {$totalUsers}\n• <b>Database Size:</b> {$dbSize} KB\n• <b>Engine:</b> SQLite WAL (20ms cURL)\n\nSelect an administrative tool below:",
                    'parse_mode'   => 'HTML',
                    'reply_markup' => getAdminDashboardMarkup()
                ]);
            } elseif ($data === 'admin_stats') {
                $total = (int)db()->query('SELECT COUNT(*) FROM users')->fetchColumn();
                $banned = (int)db()->query('SELECT COUNT(*) FROM users WHERE is_banned = 1')->fetchColumn();
                $dbSize = is_file(DB_FILE) ? round(filesize(DB_FILE) / 1024, 2) : 0;
                $logSize = is_file(__DIR__ . '/error.log') ? round(filesize(__DIR__ . '/error.log') / 1024, 2) : 0;

                bot('editMessageText', [
                    'chat_id'      => $chatId,
                    'message_id'   => $messageId,
                    'text'         => "📊 <b>Live Platform Analytics</b>\n━━━━━━━━━━━━━━━━━━━━━\n"
                                    . "• <b>Total Users:</b> " . number_format($total) . "\n"
                                    . "• <b>Active Users:</b> " . number_format($total - $banned) . "\n"
                                    . "• <b>Suspended/Banned:</b> {$banned}\n"
                                    . "• <b>Database (database.db):</b> {$dbSize} KB\n"
                                    . "• <b>Error Log (error.log):</b> {$logSize} KB\n"
                                    . "• <b>Speed:</b> ~20ms Persistent cURL",
                    'parse_mode'   => 'HTML',
                    'reply_markup' => [
                        'inline_keyboard' => [
                            [['text' => '« Back to Admin Panel', 'callback_data' => 'admin_home']]
                        ]
                    ]
                ]);
            } elseif ($data === 'admin_broadcast') {
                setState($chatId, 'admin_awaiting_broadcast');
                bot('editMessageText', [
                    'chat_id'      => $chatId,
                    'message_id'   => $messageId,
                    'text'         => "📢 <b>Universal Multi-Media Broadcast Mode</b>\n━━━━━━━━━━━━━━━━━━━━━\n"
                                    . "Send or forward the message you want to broadcast.\n\n"
                                    . "✅ <i>Supports: Text, Photos, Videos, Documents, Audio, Voice, and Stickers!</i>\n\n"
                                    . "Send <code>/cancel</code> to abort anytime.",
                    'parse_mode'   => 'HTML',
                    'reply_markup' => [
                        'inline_keyboard' => [
                            [['text' => '❌ Cancel Broadcast', 'callback_data' => 'admin_home', 'style' => 'danger']]
                        ]
                    ]
                ]);
            } elseif ($data === 'admin_users') {
                $recent = db()->query('SELECT user_id, username, first_name, is_banned FROM users ORDER BY rowid DESC LIMIT 5')->fetchAll();
                $list = "👥 <b>Recent Users & Management</b>\n━━━━━━━━━━━━━━━━━━━━━\n";
                foreach ($recent as $r) {
                    $uName = !empty($r['username']) ? '@' . clean($r['username']) : 'No @';
                    $status = !empty($r['is_banned']) ? '🔴 BANNED' : '🟢 ACTIVE';
                    $list .= "• <code>{$r['user_id']}</code> | {$uName} | {$status}\n";
                }
                $list .= "\n<b>Quick Actions:</b>\n• Ban: <code>/ban &lt;user_id&gt; &lt;reason&gt;</code>\n• Unban: <code>/unban &lt;user_id&gt;</code>";

                bot('editMessageText', [
                    'chat_id'      => $chatId,
                    'message_id'   => $messageId,
                    'text'         => $list,
                    'parse_mode'   => 'HTML',
                    'reply_markup' => [
                        'inline_keyboard' => [
                            [['text' => '« Back to Admin Panel', 'callback_data' => 'admin_home']]
                        ]
                    ]
                ]);
            } elseif ($data === 'admin_clear_logs') {
                if (is_file(__DIR__ . '/error.log')) {
                    @file_put_contents(__DIR__ . '/error.log', '');
                }
                bot('answerCallbackQuery', [
                    'callback_query_id' => $cbId,
                    'text'              => '🧹 error.log has been cleared!',
                    'show_alert'        => false
                ]);
                bot('editMessageText', [
                    'chat_id'      => $chatId,
                    'message_id'   => $messageId,
                    'text'         => "🧹 <b>Logs Cleared</b>\n\n<code>error.log</code> is now empty (0 KB).",
                    'parse_mode'   => 'HTML',
                    'reply_markup' => [
                        'inline_keyboard' => [
                            [['text' => '« Back to Admin Panel', 'callback_data' => 'admin_home']]
                        ]
                    ]
                ]);
            } elseif ($data === 'admin_close') {
                clearState($chatId);
                bot('deleteMessage', ['chat_id' => $chatId, 'message_id' => $messageId]);
            }

            http_response_code(200);
            exit('OK');
        }

        // ── Public User Callbacks ──
        if ($data === 'nav_help') {
            bot('sendMessage', [
                'chat_id'    => $chatId,
                'text'       => "📖 <b>Botlify Cloud Documentation & Help</b>\n\nThis bot is running on the <b>Botlify Native PHP 8.2+ Runtime</b> with SQLite WAL mode.\n\nUse /start to return to the main dashboard.",
                'parse_mode' => 'HTML'
            ]);
        } elseif ($data === 'nav_stats') {
            $userCount = db()->query('SELECT COUNT(*) FROM users')->fetchColumn();
            bot('sendMessage', [
                'chat_id'    => $chatId,
                'text'       => "📊 <b>Live Platform Statistics</b>\n\n• Total Registered Users: <b>" . number_format((int)$userCount) . "</b>\n• Database Engine: <b>SQLite 3 (database.db)</b>\n• Execution Speed: <b>~20ms cURL</b>",
                'parse_mode' => 'HTML'
            ]);
        }

        http_response_code(200);
        exit('OK');
    }

    // B. Handle Incoming Messages
    if (isset($update['message'])) {
        $msg       = $update['message'];
        $chatId    = $msg['chat']['id'] ?? 0;
        $userId    = (int)($msg['from']['id'] ?? 0);
        $firstName = (string)($msg['from']['first_name'] ?? 'User');
        $username  = (string)($msg['from']['username'] ?? '');
        $text      = trim((string)($msg['text'] ?? ''));

        if (!$chatId || !$userId) {
            http_response_code(200);
            exit('OK');
        }

        // Register or refresh user in database.db
        $user = registerOrUpdateUser($userId, $username, $firstName);

        // Ban Firewall: Intercepts banned users
        if (!empty($user['is_banned'])) {
            $reason = !empty($user['ban_reason']) ? clean((string)$user['ban_reason']) : 'Violation of bot terms';
            bot('sendMessage', [
                'chat_id'      => $chatId,
                'text'         => "⛔ <b>Access Denied: Your Account is Suspended</b>\n\n⚠️ <b>Reason:</b> <i>{$reason}</i>",
                'parse_mode'   => 'HTML',
                'reply_markup' => ['remove_keyboard' => true]
            ]);
            http_response_code(200);
            exit('OK');
        }

        // Global /cancel command
        if ($text === '/cancel') {
            clearState($chatId);
            bot('sendMessage', [
                'chat_id'      => $chatId,
                'text'         => '❌ <i>Operation cancelled.</i>',
                'parse_mode'   => 'HTML',
                'reply_markup' => ['remove_keyboard' => true]
            ]);
            http_response_code(200);
            exit('OK');
        }

        // ── Active FSM Interceptor ──
        $userState = getState($chatId);
        if ($userState['state'] === 'admin_awaiting_broadcast' && isAdmin($userId)) {
            clearState($chatId);
            $msgId = (int)($msg['message_id'] ?? 0);
            bot('sendChatAction', ['chat_id' => $chatId, 'action' => 'typing']);

            $stmt = db()->query('SELECT user_id FROM users WHERE is_banned = 0');
            $allUsers = $stmt->fetchAll(PDO::FETCH_COLUMN);

            $sent = 0;
            $failed = 0;
            foreach ($allUsers as $targetUid) {
                // Universal copyMessage: clones text, photos, videos, stickers, voice with zero re-upload!
                $res = bot('copyMessage', [
                    'chat_id'      => $targetUid,
                    'from_chat_id' => $chatId,
                    'message_id'   => $msgId
                ]);
                if (!empty($res['ok'])) {
                    $sent++;
                } else {
                    $failed++;
                }
                usleep(38000); // 38ms safe sleep (~26 msg/sec anti-flood)
            }

            // Log broadcast
            $logStmt = db()->prepare('INSERT INTO broadcast_logs (admin_id, sent_count, failed_count, message_text) VALUES (?, ?, ?, ?)');
            $logStmt->execute([(string)$userId, $sent, $failed, $text !== '' ? $text : '[Media/Attachment]']);

            bot('sendMessage', [
                'chat_id'      => $chatId,
                'text'         => "✅ <b>Universal Broadcast Complete!</b>\n━━━━━━━━━━━━━━━━━━━━━\n• Successfully Sent: <b>{$sent}</b>\n• Failed / Blocked: <b>{$failed}</b>\n• Total Reached: <b>" . ($sent + $failed) . "</b>",
                'parse_mode'   => 'HTML',
                'reply_markup' => getAdminDashboardMarkup()
            ]);
            http_response_code(200);
            exit('OK');
        }

        // ── Admin Command: /admin ──
        if ($text === '/admin') {
            if (!isAdmin($userId)) {
                bot('sendMessage', [
                    'chat_id'    => $chatId,
                    'text'       => '⛔ <i>Access denied. This command is restricted to the bot administrator.</i>',
                    'parse_mode' => 'HTML'
                ]);
                http_response_code(200);
                exit('OK');
            }

            clearState($chatId);
            $totalUsers = (int)db()->query('SELECT COUNT(*) FROM users')->fetchColumn();
            $dbSize = is_file(DB_FILE) ? round(filesize(DB_FILE) / 1024, 2) : 0;

            bot('sendMessage', [
                'chat_id'      => $chatId,
                'text'         => "👑 <b>Bot Admin Control Suite</b>\n\n• <b>Total Users:</b> {$totalUsers}\n• <b>Database Size:</b> {$dbSize} KB\n• <b>Engine:</b> SQLite WAL (20ms cURL)\n\nSelect an administrative tool below:",
                'parse_mode'   => 'HTML',
                'reply_markup' => getAdminDashboardMarkup()
            ]);
            http_response_code(200);
            exit('OK');
        }

        // ── Admin Command: /ban <user_id> <reason> ──
        if (str_starts_with($text, '/ban') && isAdmin($userId)) {
            $parts = explode(' ', $text, 3);
            $targetUid = (int)($parts[1] ?? 0);
            $banReason = trim($parts[2] ?? 'Banned by administrator');

            if ($targetUid <= 0) {
                bot('sendMessage', ['chat_id' => $chatId, 'text' => "⚠️ <b>Usage:</b> <code>/ban &lt;user_id&gt; &lt;reason&gt;</code>", 'parse_mode' => 'HTML']);
                http_response_code(200);
                exit('OK');
            }

            $st = db()->prepare('UPDATE users SET is_banned = 1, ban_reason = ? WHERE user_id = ?');
            $st->execute([$banReason, $targetUid]);

            bot('sendMessage', [
                'chat_id'    => $chatId,
                'text'       => "🔴 <b>User Banned Successfully</b>\n\n• <b>User ID:</b> <code>{$targetUid}</code>\n• <b>Reason:</b> {$banReason}",
                'parse_mode' => 'HTML'
            ]);
            http_response_code(200);
            exit('OK');
        }

        // ── Admin Command: /unban <user_id> ──
        if (str_starts_with($text, '/unban') && isAdmin($userId)) {
            $parts = explode(' ', $text, 2);
            $targetUid = (int)($parts[1] ?? 0);

            if ($targetUid <= 0) {
                bot('sendMessage', ['chat_id' => $chatId, 'text' => "⚠️ <b>Usage:</b> <code>/unban &lt;user_id&gt;</code>", 'parse_mode' => 'HTML']);
                http_response_code(200);
                exit('OK');
            }

            $st = db()->prepare('UPDATE users SET is_banned = 0, ban_reason = NULL WHERE user_id = ?');
            $st->execute([$targetUid]);

            bot('sendMessage', [
                'chat_id'    => $chatId,
                'text'       => "🟢 <b>User Unbanned Successfully</b>\n\n• <b>User ID:</b> <code>{$targetUid}</code>",
                'parse_mode' => 'HTML'
            ]);
            http_response_code(200);
            exit('OK');
        }

        // ── General User Command: /start ──
        if ($text === '/start') {
            $welcomeText = "👋 <b>Welcome, " . clean($firstName) . "!</b>\n\n"
                         . "Your high-speed Telegram bot is online and powered by <b>Botlify Cloud</b>.\n\n"
                         . "• <b>Runtime:</b> PHP 8.2+ Serverless\n"
                         . "• <b>Storage:</b> SQLite WAL (<code>database.db</code>)\n"
                         . "• <b>Self-Healing:</b> Auto-migrating database schema\n"
                         . "• <b>Latency:</b> Sub-20ms Persistent cURL";

            bot('sendMessage', [
                'chat_id'           => $chatId,
                'text'              => $welcomeText,
                'parse_mode'        => 'HTML',
                'message_effect_id' => '5104841245755180586', // Full-screen confetti
                'reply_markup'      => [
                    'inline_keyboard' => [
                        [
                            ['text' => '📊 Live Stats', 'callback_data' => 'nav_stats', 'style' => 'primary'],
                            ['text' => '📖 Help Guide', 'callback_data' => 'nav_help']
                        ],
                        [
                            ['text' => '🌐 Botlify Cloud', 'url' => 'https://botlify.cloud']
                        ]
                    ]
                ]
            ]);
            http_response_code(200);
            exit('OK');
        }

        // Fallback response for unhandled text
        bot('sendMessage', [
            'chat_id'    => $chatId,
            'text'       => "🤖 <i>Message received. Use /start to explore the bot dashboard.</i>",
            'parse_mode' => 'HTML'
        ]);
    }

    http_response_code(200);
    echo 'OK';
} catch (Throwable $e) {
    error_log(date('[Y-m-d H:i:s] ') . 'Bot Error: ' . $e->getMessage() . ' in ' . $e->getFile() . ':' . $e->getLine());
    http_response_code(200);
    echo 'OK';
}
```

---

## 4. 📖 Master Guide: Telegram Bot Making on Botlify Cloud

Welcome to the comprehensive development guide for building high-performance Telegram bots on **Botlify Cloud**. This guide covers everything from beginner setup to advanced architectures, including our modern **Inline and Reply Keyboard Button Color Styling (`primary`, `success`, `danger`)**, SQLite database integration, cron automations, and best practices.

---

### 4.1. Architecture & Folder Structure

Every bot on Botlify Cloud operates in its own isolated workspace with dedicated compute, storage quotas, and a sandboxed SQLite database:

```text
/storage/users/{chat_id}/bots/{bot_username}/
├── index.php             # Main webhook execution entrypoint
├── .env                  # Protected credentials and custom environment variables
├── database.db           # Bot-isolated persistent SQLite 3 database (WAL mode)
├── cron.php              # (Optional) Automated periodic cron script
├── handlers/             # (Optional) Modular PHP action handlers
└── error.log             # Auto-generated runtime error log
```

When a user interacts with your bot on Telegram, Telegram delivers an HTTP `POST` JSON payload directly to your bot's `index.php`.

---

### 4.2. Environment Variables & Credentials (.env)

Your bot's `.env` file is generated automatically when you deploy. It securely holds your bot token and configuration without exposing them in public repositories:

```ini
BOT_TOKEN="1234567890:AAHxyz..."
BOT_USERNAME="MyAwesomeBot"
BOT_ID="1234567890"
ADMIN_CHAT_ID="987654321"
OWNER_CHAT_ID="987654321"
CREATED_AT="1726000000"
```

#### Loading `.env` in PHP:
```php
$envFile = __DIR__ . '/.env';
$ENV = [];
if (is_file($envFile)) {
    foreach (file($envFile, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES) as $line) {
        $line = trim($line);
        if ($line === '' || str_starts_with($line, '#') || !str_contains($line, '=')) continue;
        [$k, $v] = explode('=', $line, 2);
        $ENV[trim($k)] = trim(trim($v), '"\'');
    }
}

define('BOT_TOKEN', $ENV['BOT_TOKEN'] ?? (getenv('BOT_TOKEN') ?: ''));
define('ADMIN_CHAT_ID', (string)($ENV['ADMIN_CHAT_ID'] ?? (getenv('ADMIN_CHAT_ID') ?: '')));
define('ADMIN_ID', ADMIN_CHAT_ID);
define('OWNER_CHAT_ID', (string)($ENV['OWNER_CHAT_ID'] ?? (getenv('OWNER_CHAT_ID') ?: '')));
define('BOT_USERNAME', (string)($ENV['BOT_USERNAME'] ?? (getenv('BOT_USERNAME') ?: '')));
define('BOT_ID', (string)($ENV['BOT_ID'] ?? (getenv('BOT_ID') ?: '')));
```

> **🛡️ Isolated Runtime Guarantee:** The Botlify platform isolates the child bot execution context (`FBH_CHILD_BOT_CONTEXT`). The `BOT_TOKEN` belongs strictly to this hosted bot. Botlify's main platform bot will never intercept or respond to child bot interactions.

---

### 4.3. Incoming Updates & Telegram Bot API Handler

#### Handling the Webhook:
```php
<?php
declare(strict_types=1);

// Capture Telegram's incoming JSON update
$rawUpdate = file_get_contents('php://input');
$update = json_decode((string)$rawUpdate, true);

if (!$update) {
    echo "Bot is online and waiting for Telegram updates.";
    exit;
}

// Extract message or callback query
$message = $update['message'] ?? null;
$callback = $update['callback_query'] ?? null;
```

#### Clean API Request Helper (`bot()`):
```php
function bot(string $method, array $params = []): array {
    if (!defined('BOT_TOKEN') || BOT_TOKEN === '') return ['ok' => false];
    static $ch = null;
    if ($ch === null || !($ch instanceof \CurlHandle || is_resource($ch))) {
        $ch = curl_init();
    }
    $opts = [
        CURLOPT_URL            => 'https://api.telegram.org/bot' . BOT_TOKEN . '/' . $method,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_POST           => true,
        CURLOPT_POSTFIELDS     => json_encode($params, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES),
        CURLOPT_HTTPHEADER     => ['Content-Type: application/json; charset=utf-8'],
        CURLOPT_CONNECTTIMEOUT => 8,
        CURLOPT_TIMEOUT        => 15,
        CURLOPT_IPRESOLVE      => CURL_IPRESOLVE_V4,
        CURLOPT_TCP_NODELAY    => true,
        CURLOPT_DNS_CACHE_TIMEOUT => 3600,
        CURLOPT_SSL_VERIFYPEER => false,
        CURLOPT_SSL_VERIFYHOST => false,
    ];
    if (defined('CURL_HTTP_VERSION_2TLS')) {
        $opts[CURLOPT_HTTP_VERSION] = CURL_HTTP_VERSION_2TLS;
    }
    curl_setopt_array($ch, $opts);
    $res = curl_exec($ch);
    return json_decode((string)$res, true) ?: ['ok' => false];
}

// Convenient shortcut for sendMessage
function sendMessage($chatId, string $text, array $extra = []): array {
    return bot('sendMessage', array_merge([
        'chat_id'    => $chatId,
        'text'       => $text,
        'parse_mode' => 'HTML'
    ], $extra));
}
```

---

### 4.4. 🎨 Keyboard Menus & Button Color Styling

Botlify Cloud supports button color styling for both **Inline Keyboards** and **Reply Keyboards**.

#### 🎨 Style to Color Mapping:
| Style Attribute | Rendered Button Color | Best Use Cases |
|---|---|---|
| `'style' => 'primary'` | 🔵 **Blue** | Main call-to-action, Confirm, Open, Start, Next |
| `'style' => 'success'` | 🟢 **Green** | Buy, Deposit, Approve, Completed, Accept, Add |
| `'style' => 'danger'`  | 🔴 **Red** | Delete, Cancel, Reject, Withdraw, Ban, Clear |
| (omitted / default)    | ⚪ **Standard/Gray** | Back, Settings, Info, Navigation |

---

#### Inline Keyboard with Button Colors

Inline keyboards appear directly attached to the message. You can specify `'style'` for any button:

```php
$inlineKeyboard = [
    'inline_keyboard' => [
        [
            [
                'text' => '🚀 Launch App',
                'callback_data' => 'action_launch',
                'style' => 'primary' // 🔵 Blue
            ],
            [
                'text' => '💳 Deposit USDT',
                'callback_data' => 'action_deposit',
                'style' => 'success' // 🟢 Green
            ]
        ],
        [
            [
                'text' => '🗑️ Delete Project',
                'callback_data' => 'action_delete',
                'style' => 'danger' // 🔴 Red
            ]
        ]
    ]
];

$reply_markup = json_encode($inlineKeyboard);

sendMessage($chatId, "<b>Welcome to Bot Dashboard!</b>\nPlease choose an option:", [
    'reply_markup' => $reply_markup
]);
```

---

#### Reply Keyboard with Button Colors

Reply keyboards stay fixed at the bottom of the user's chat screen:

```php
$replyKeyboard = [
    'keyboard' => [
        [
            [
                'text' => '🟢 Activate VIP Plan',
                'style' => 'success' // 🟢 Green
            ],
            [
                'text' => '🔵 My Wallet & Stats',
                'style' => 'primary' // 🔵 Blue
            ]
        ],
        [
            [
                'text' => '🔴 Cancel Order',
                'style' => 'danger' // 🔴 Red
            ],
            [
                'text' => '⚙️ Settings' // ⚪ Standard
            ]
        ]
    ],
    'resize_keyboard' => true,
    'one_time_keyboard' => false
];

$reply_markup = json_encode($replyKeyboard);

sendMessage($chatId, "Main menu loaded with colored buttons:", [
    'reply_markup' => $reply_markup
]);
```

---

#### Combined Interactive Menu Grid

Here is a full pattern for an interactive confirmation prompt:

```php
$confirmMenu = [
    'inline_keyboard' => [
        [
            [
                'text' => '✅ Confirm & Proceed',
                'callback_data' => 'confirm_yes',
                'style' => 'success' // 🟢 Green
            ],
            [
                'text' => '❌ Cancel & Abort',
                'callback_data' => 'confirm_no',
                'style' => 'danger' // 🔴 Red
            ]
        ],
        [
            [
                'text' => 'ℹ️ View Documentation',
                'url' => 'https://t.me/your_channel',
                'style' => 'primary' // 🔵 Blue
            ]
        ]
    ]
];
```

---

### 4.5. Callback Queries & Interactive Navigation

When users click an inline button, Telegram sends a `callback_query`. Always respond using `answerCallbackQuery` so the button stops loading:

```php
if ($callback) {
    $callbackId = $callback['id'];
    $data = $callback['data'] ?? '';
    $chatId = $callback['message']['chat']['id'] ?? 0;
    $messageId = $callback['message']['message_id'] ?? 0;

    // 1. Acknowledge the click immediately
    bot('answerCallbackQuery', [
        'callback_query_id' => $callbackId,
        'text'              => 'Loading…',
        'show_alert'        => false
    ]);

    // 2. Handle actions
    if ($data === 'action_deposit') {
        bot('editMessageText', [
            'chat_id'    => $chatId,
            'message_id' => $messageId,
            'text'       => "<b>Deposit Funds</b>\nSend USDT (TRC20) to your balance.",
            'parse_mode' => 'HTML',
            'reply_markup' => json_encode([
                'inline_keyboard' => [
                    [['text' => '⬅️ Back to Menu', 'callback_data' => 'main_menu', 'style' => 'primary']]
                ]
            ])
        ]);
    }
}
```

---

### 4.6. SQLite Database Integration & Self-Healing Schemas (`database.db`)

Each bot has access to its own ultra-fast, local SQLite database file in `database.db` directly in the bot root folder.

#### Production SQLite Connection with WAL Mode & Busy Timeout:
```php
function db(): PDO {
    static $pdo = null;
    if ($pdo === null) {
        $dbPath = __DIR__ . '/database.db';
        $pdo = new PDO('sqlite:' . $dbPath, null, null, [
            PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
            PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
            PDO::ATTR_TIMEOUT            => 5,
        ]);
        $pdo->exec('PRAGMA journal_mode = WAL;');
        $pdo->exec('PRAGMA synchronous = NORMAL;');
        $pdo->exec('PRAGMA busy_timeout = 5000;');
    }
    return $pdo;
}

// 🛡️ Self-Healing Column Migrator (CRITICAL):
// In SQLite, CREATE TABLE IF NOT EXISTS does NOT add new columns when switching or updating bot code!
// This helper auto-adds missing columns on the fly so users never get "no such column" crashes or need to delete database.db!
function ensureColumn(PDO $pdo, string $table, string $column, string $type = 'TEXT'): void {
    try {
        $cols = $pdo->query("PRAGMA table_info({$table})")->fetchAll(PDO::FETCH_COLUMN, 1);
        if (!in_array($column, $cols, true)) {
            $pdo->exec("ALTER TABLE {$table} ADD COLUMN {$column} {$type}");
        }
    } catch (Throwable $e) {}
}

// Initialize tables
db()->exec("CREATE TABLE IF NOT EXISTS users (
    chat_id TEXT PRIMARY KEY,
    username TEXT DEFAULT '',
    first_name TEXT DEFAULT '',
    balance REAL DEFAULT 0.00,
    created_at INTEGER DEFAULT 0,
    last_active INTEGER DEFAULT 0,
    is_banned INTEGER DEFAULT 0
)");

// Ensure columns exist even if table was created by a previous bot
ensureColumn(db(), 'users', 'balance', 'REAL DEFAULT 0.00');
ensureColumn(db(), 'users', 'is_banned', 'INTEGER DEFAULT 0');
ensureColumn(db(), 'users', 'created_at', 'INTEGER DEFAULT 0');
ensureColumn(db(), 'users', 'last_active', 'INTEGER DEFAULT 0');
```

#### User Registration & Balance Tracking:
```php
function registerUser(PDO $db, array $from): array {
    $chatId = (string) $from['id'];
    $username = $from['username'] ?? '';
    $firstName = $from['first_name'] ?? 'User';

    $stmt = $db->prepare("INSERT INTO users (chat_id, username, first_name, last_active)
        VALUES (?, ?, ?, datetime('now'))
        ON CONFLICT(chat_id) DO UPDATE SET
            username = excluded.username,
            first_name = excluded.first_name,
            last_active = datetime('now')");
    $stmt->execute([$chatId, $username, $firstName]);

    $getUser = $db->prepare("SELECT * FROM users WHERE chat_id = ?");
    $getUser->execute([$chatId]);
    return $getUser->fetch() ?: [];
}
```

---

### 4.7. Automated Background Cron Jobs (`cron.php`)

To perform automated background tasks (daily reports, subscription renewals, database cleanups):

1. Create a `cron.php` file in your bot root folder:
```php
<?php
declare(strict_types=1);

require_once __DIR__ . '/index.php'; // Or load your bot functions

// Connect to bot DB
$db = new PDO('sqlite:' . __DIR__ . '/storage/database.db');

// Example: Send automated reminder to users inactive for 3 days
$stmt = $db->query("SELECT chat_id FROM users WHERE last_active < datetime('now', '-3 days') LIMIT 50");
$users = $stmt->fetchAll(PDO::FETCH_COLUMN);

foreach ($users as $chatId) {
    sendMessage($chatId, "👋 We missed you! Check out our new features today.", [
        'reply_markup' => json_encode([
            'inline_keyboard' => [
                [['text' => '🚀 Open Dashboard', 'callback_data' => 'main_menu', 'style' => 'primary']]
            ]
        ])
    ]);
    usleep(50000); // 50ms throttle
}

echo "Cron finished successfully at " . date('Y-m-d H:i:s');
```

2. Schedule the cron job in your Mini App under **Variables & Cron** -> **+ New Cron Task**, or through the Developer API / MCP!

---

### 4.8. Broadcast & User Tracking

Send mass notifications (Text, Image, Video, or GIF) safely with rate-limiting or via Botlify's high-speed parallel MCP Broadcast Engine:

#### 1. In-Bot PHP Broadcast Helper:
```php
function broadcastMessage(PDO $db, string $text, ?string $replyMarkup = null, string $type = 'text', string $media = ''): array {
    $stmt = $db->query("SELECT chat_id FROM users");
    $total = 0; $sent = 0; $failed = 0;

    while ($chatId = $stmt->fetchColumn()) {
        $total++;
        $extra = [];
        if ($replyMarkup) $extra['reply_markup'] = $replyMarkup;

        if ($type === 'photo' || $type === 'image') {
            $res = bot('sendPhoto', array_merge(['chat_id' => $chatId, 'photo' => $media, 'caption' => $text], $extra));
        } elseif ($type === 'video') {
            $res = bot('sendVideo', array_merge(['chat_id' => $chatId, 'video' => $media, 'caption' => $text], $extra));
        } elseif ($type === 'animation' || $type === 'gif') {
            $res = bot('sendAnimation', array_merge(['chat_id' => $chatId, 'animation' => $media, 'caption' => $text], $extra));
        } else {
            $res = bot('sendMessage', array_merge(['chat_id' => $chatId, 'text' => $text], $extra));
        }

        if (!empty($res['ok'])) {
            $sent++;
        } else {
            $failed++;
        }
        usleep(35000); // Sleep 35ms (Telegram limit: ~30 msg/sec)
    }

    return ['total' => $total, 'sent' => $sent, 'failed' => $failed];
}
```

#### 2. High-Speed MCP Broadcast API (`send_broadcast`):
You can trigger instant parallel broadcasts from the Botlify MCP server with full media support:
- **Text Broadcast**: `send_broadcast(bot_id, type="text", message="Hello world!")`
- **Image Broadcast**: `send_broadcast(bot_id, type="image", media_url="https://.../pic.jpg", message="Check this out!")`
- **Video Broadcast**: `send_broadcast(bot_id, type="video", media_url="https://.../video.mp4", message="New Tutorial")`
- **GIF Broadcast**: `send_broadcast(bot_id, type="gif", media_url="https://.../anim.gif", message="🎉 Celebration")`
- **With Buttons**: Pass `inline_keyboard: [[{"text": "Visit Website", "url": "https://example.com"}]]`

---

### 4.9. Error Handling & Webhook Storm Prevention

Always wrap your main logic in a `try...catch` block. When an error occurs, acknowledge Telegram with HTTP 200 OK immediately to stop Telegram from endlessly retrying:

```php
try {
    // Your bot code here
} catch (Throwable $e) {
    // 1. Immediately acknowledge webhook with HTTP 200 to prevent Telegram retry storms
    if (!headers_sent()) {
        http_response_code(200);
        header('Content-Type: application/json; charset=utf-8');
        echo json_encode(['ok' => true, 'handled_error' => true]);
        if (function_exists('fastcgi_finish_request')) {
            fastcgi_finish_request();
        }
    }

    // 2. Log clean error to error.log
    $errorMsg = "[" . date('d-M-Y H:i:s e') . "] Uncaught " . get_class($e) . ": " . $e->getMessage() . " in " . basename($e->getFile()) . ":" . $e->getLine() . "\n";
    @file_put_contents(__DIR__ . '/error.log', $errorMsg, FILE_APPEND);

    // 3. Notify bot admin if configured
    if (defined('ADMIN_CHAT_ID') && ADMIN_CHAT_ID !== '') {
        bot('sendMessage', [
            'chat_id' => ADMIN_CHAT_ID,
            'text' => "⚠️ <b>Bot Exception:</b>\n<code>" . htmlspecialchars($e->getMessage()) . "</code>",
            'parse_mode' => 'HTML'
        ]);
    }
}
```

---

### 4.10. 🚀 Full Production Ready Boilerplates

#### Boilerplate 1: Modern Styled Keyboard Bot
Save as `index.php`:

```php
<?php
declare(strict_types=1);

// 1. Load Credentials
$envFile = __DIR__ . '/.env';
$ENV = [];
if (is_file($envFile)) {
    foreach (file($envFile, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES) as $l) {
        if ($l && $l[0] !== '#' && str_contains($l, '=')) {
            [$k, $v] = explode('=', $l, 2);
            $ENV[trim($k)] = trim(trim($v), '"\'');
        }
    }
}

define('BOT_TOKEN', $ENV['BOT_TOKEN'] ?? '');
if (BOT_TOKEN === '') exit('No BOT_TOKEN');

// 2. Telegram Helper
function bot(string $method, array $params = []): array {
    if (!defined('BOT_TOKEN') || BOT_TOKEN === '') return ['ok' => false];
    static $ch = null;
    if ($ch === null || !($ch instanceof \CurlHandle || is_resource($ch))) {
        $ch = curl_init();
    }
    $opts = [
        CURLOPT_URL            => 'https://api.telegram.org/bot' . BOT_TOKEN . '/' . $method,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_POST           => true,
        CURLOPT_POSTFIELDS     => json_encode($params, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES),
        CURLOPT_HTTPHEADER     => ['Content-Type: application/json; charset=utf-8'],
        CURLOPT_CONNECTTIMEOUT => 8,
        CURLOPT_TIMEOUT        => 15,
        CURLOPT_IPRESOLVE      => CURL_IPRESOLVE_V4,
        CURLOPT_TCP_NODELAY    => true,
        CURLOPT_DNS_CACHE_TIMEOUT => 3600,
        CURLOPT_SSL_VERIFYPEER => false,
        CURLOPT_SSL_VERIFYHOST => false,
    ];
    if (defined('CURL_HTTP_VERSION_2TLS')) {
        $opts[CURLOPT_HTTP_VERSION] = CURL_HTTP_VERSION_2TLS;
    }
    curl_setopt_array($ch, $opts);
    $res = curl_exec($ch);
    return json_decode((string)$res, true) ?: ['ok' => false];
}

// 3. Handle Updates
$update = json_decode((string)file_get_contents('php://input'), true);
if (!$update) exit('Bot is active');

$msg = $update['message'] ?? null;
$cb  = $update['callback_query'] ?? null;

if ($msg && isset($msg['text'])) {
    $chatId = $msg['chat']['id'];
    $text = trim($msg['text']);

    if ($text === '/start') {
        // Styled Inline Menu
        $inlineMenu = [
            'inline_keyboard' => [
                [
                    ['text' => '🚀 Launch Portal', 'callback_data' => 'launch', 'style' => 'primary'],
                    ['text' => '💎 Upgrade VIP', 'callback_data' => 'upgrade', 'style' => 'success']
                ],
                [
                    ['text' => '🛑 Stop Service', 'callback_data' => 'stop', 'style' => 'danger']
                ]
            ]
        ];

        // Styled Reply Keyboard
        $replyMenu = [
            'keyboard' => [
                [
                    ['text' => '🟢 Deposit Funds', 'style' => 'success'],
                    ['text' => '🔵 My Profile', 'style' => 'primary']
                ],
                [
                    ['text' => '🔴 Close Menu', 'style' => 'danger']
                ]
            ],
            'resize_keyboard' => true
        ];

        bot('sendMessage', [
            'chat_id'      => $chatId,
            'text'         => "👋 <b>Welcome!</b>\nEnjoy our modern styled keyboards:",
            'parse_mode'   => 'HTML',
            'reply_markup' => json_encode($inlineMenu)
        ]);
    }
}

if ($cb) {
    $cbId = $cb['id'];
    $data = $cb['data'] ?? '';
    $chatId = $cb['message']['chat']['id'];
    $msgId  = $cb['message']['message_id'];

    bot('answerCallbackQuery', ['callback_query_id' => $cbId, 'text' => "Selected: {$data}"]);

    if ($data === 'launch') {
        bot('editMessageText', [
            'chat_id'      => $chatId,
            'message_id'   => $msgId,
            'text'         => "🚀 <b>Portal Active</b>\nChoose an action below:",
            'parse_mode'   => 'HTML',
            'reply_markup' => json_encode([
                'inline_keyboard' => [
                    [['text' => '⬅️ Back', 'callback_data' => 'back', 'style' => 'primary']]
                ]
            ])
        ]);
    }
}
```

---

#### Boilerplate 2: Full SQLite Database Bot
Save as `index.php`:

```php
<?php
declare(strict_types=1);

// 1. Load Env
$envFile = __DIR__ . '/.env';
$ENV = [];
if (is_file($envFile)) {
    foreach (file($envFile, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES) as $l) {
        if ($l && $l[0] !== '#' && str_contains($l, '=')) {
            [$k, $v] = explode('=', $l, 2);
            $ENV[trim($k)] = trim(trim($v), '"\'');
        }
    }
}
define('BOT_TOKEN', $ENV['BOT_TOKEN'] ?? '');
if (BOT_TOKEN === '') exit('No token');

// 2. Database Connection
$db = new PDO('sqlite:' . __DIR__ . '/storage/database.db');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->exec("CREATE TABLE IF NOT EXISTS users (
    chat_id TEXT PRIMARY KEY,
    username TEXT,
    balance REAL DEFAULT 0,
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP
)");

// 3. Telegram API Helper
function bot(string $method, array $params = []): array {
    if (!defined('BOT_TOKEN') || BOT_TOKEN === '') return ['ok' => false];
    static $ch = null;
    if ($ch === null || !($ch instanceof \CurlHandle || is_resource($ch))) {
        $ch = curl_init();
    }
    $opts = [
        CURLOPT_URL            => 'https://api.telegram.org/bot' . BOT_TOKEN . '/' . $method,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_POST           => true,
        CURLOPT_POSTFIELDS     => json_encode($params, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES),
        CURLOPT_HTTPHEADER     => ['Content-Type: application/json; charset=utf-8'],
        CURLOPT_CONNECTTIMEOUT => 8,
        CURLOPT_TIMEOUT        => 15,
        CURLOPT_IPRESOLVE      => CURL_IPRESOLVE_V4,
        CURLOPT_TCP_NODELAY    => true,
        CURLOPT_DNS_CACHE_TIMEOUT => 3600,
        CURLOPT_SSL_VERIFYPEER => false,
        CURLOPT_SSL_VERIFYHOST => false,
    ];
    if (defined('CURL_HTTP_VERSION_2TLS')) {
        $opts[CURLOPT_HTTP_VERSION] = CURL_HTTP_VERSION_2TLS;
    }
    curl_setopt_array($ch, $opts);
    $res = curl_exec($ch);
    return json_decode((string)$res, true) ?: ['ok' => false];
}

// 4. Update Processing
$update = json_decode((string)file_get_contents('php://input'), true);
if (!$update) exit('Online');

$msg = $update['message'] ?? null;
if ($msg && isset($msg['text'])) {
    $chatId = (string) $msg['chat']['id'];
    $text = trim($msg['text']);
    $user = $msg['from'] ?? [];

    // Register user
    $st = $db->prepare("INSERT OR IGNORE INTO users (chat_id, username) VALUES (?, ?)");
    $st->execute([$chatId, $user['username'] ?? '']);

    if ($text === '/start') {
        $st = $db->prepare("SELECT balance FROM users WHERE chat_id = ?");
        $st->execute([$chatId]);
        $balance = (float)$st->fetchColumn();

        $menu = [
            'inline_keyboard' => [
                [
                    ['text' => '➕ Deposit 5 USDT', 'callback_data' => 'add_funds', 'style' => 'success'],
                    ['text' => '📊 Account Stats', 'callback_data' => 'stats', 'style' => 'primary']
                ],
                [
                    ['text' => '❌ Reset Account', 'callback_data' => 'reset', 'style' => 'danger']
                ]
            ]
        ];

        bot('sendMessage', [
            'chat_id'      => $chatId,
            'text'         => "👋 <b>Welcome!</b>\n💰 Your Balance: <b>{$balance} USDT</b>",
            'parse_mode'   => 'HTML',
            'reply_markup' => json_encode($menu)
        ]);
    }
}

$cb = $update['callback_query'] ?? null;
if ($cb) {
    $chatId = (string)$cb['message']['chat']['id'];
    $msgId  = $cb['message']['message_id'];
    $data   = $cb['data'] ?? '';

    if ($data === 'add_funds') {
        $db->prepare("UPDATE users SET balance = balance + 5 WHERE chat_id = ?")->execute([$chatId]);
        bot('answerCallbackQuery', ['callback_query_id' => $cb['id'], 'text' => '+5 USDT Added!']);
        
        $st = $db->prepare("SELECT balance FROM users WHERE chat_id = ?");
        $st->execute([$chatId]);
        $newBal = (float)$st->fetchColumn();

        bot('editMessageText', [
            'chat_id'    => $chatId,
            'message_id' => $msgId,
            'text'       => "✅ <b>Deposit Successful!</b>\nNew Balance: <b>{$newBal} USDT</b>",
            'parse_mode' => 'HTML',
            'reply_markup' => json_encode([
                'inline_keyboard' => [
                    [['text' => '⬅️ Back to Menu', 'callback_data' => 'back', 'style' => 'primary']]
                ]
            ])
        ]);
    }
}
```

---

### 4.11. ✨ Custom Animated & Static Emojis (`<tg-emoji>` & MarkdownV2)

Telegram Bot API supports custom emojis across messages, captions, and notifications. Custom emojis render as animated or styled stickers directly inline with text.

#### 📌 Formatting Specifications:

##### 1. HTML Formatting (`parse_mode: 'HTML'`):
Wrap the fallback standard emoji inside the `<tg-emoji>` tag with the `emoji-id` attribute:
```html
Welcome to our bot! <tg-emoji emoji-id="5368324170671202286">🔥</tg-emoji>
Congratulations, you unlocked VIP <tg-emoji emoji-id="5449987823521096781">⭐</tg-emoji>
```

> [!IMPORTANT]
> **Fallback Emoji Requirement**: The tag must wrap a standard Unicode emoji (like `🔥` or `⭐`). Clients that cannot render custom emojis (or web clients without Premium) will gracefully fall back to this character.

##### 2. MarkdownV2 Formatting (`parse_mode: 'MarkdownV2'`):
```markdown
Welcome to our bot\! \![🔥](tg://emoji?id=5368324170671202286)
Congratulations, you unlocked VIP \![⭐](tg://emoji?id=5449987823521096781)
```

#### 🔍 How to Find Custom Emoji IDs:
1. **Telegram Web Inspector**: Open Telegram Web (A or K version), right-click on an emoji from a sticker pack, and inspect element to find `data-custom-emoji-id` or `custom_emoji_id`.
2. **Bot Message Echo**: Send the custom emoji to your bot in Telegram and print `$update['message']['entities']`. Look for an entity where `'type' === 'custom_emoji'` and read `'custom_emoji_id'`.

#### 💡 PHP Helper Function for Custom Emojis:
```php
function tg_emoji(string $emojiId, string $fallback = '⭐'): string {
    return "<tg-emoji emoji-id=\"{$emojiId}\">{$fallback}</tg-emoji>";
}

// Usage in messages:
$star = tg_emoji('5449987823521096781', '⭐');
$fire = tg_emoji('5368324170671202286', '🔥');

bot('sendMessage', [
    'chat_id'    => $chatId,
    'text'       => "{$star} <b>Premium Store Active</b> {$fire}\n\nUpgrade your account today!",
    'parse_mode' => 'HTML'
]);
```

---

### 4.12. ⭐ Telegram Stars Payments System (`currency: XTR`)

**Telegram Stars (`XTR`)** is the official digital currency for purchasing digital goods, subscriptions, and services inside Telegram bots and Mini Apps.

#### ⚠️ Critical Telegram Stars Rules:
1. **Currency**: Must be strictly set to `"XTR"`.
2. **`provider_token`**: **MUST BE COMPLETELY OMITTED!** Do not set it to an empty string, null, or false. Delete the key entirely from the `sendInvoice` payload.
3. **Prices Amount**: Integer amount of Stars (e.g., `50` means 50 Stars; no cents or decimal multiplication).
4. **Pre-Checkout Timeout**: You **must** answer `pre_checkout_query` within **10 seconds** via `answerPreCheckoutQuery`, or Telegram will cancel the order.

#### 🔄 The 3-Step Stars Payment Lifecycle:

```
[User clicks Buy Button] 
       │
       ▼
1. Bot calls sendInvoice (currency: "XTR", NO provider_token)
       │
       ▼
[Telegram displays native Star payment modal & user confirms]
       │
       ▼
2. Telegram sends update: pre_checkout_query
   Bot immediately answers with: answerPreCheckoutQuery (ok: true)
       │
       ▼
3. Telegram processes payment and sends update: successful_payment
   Bot delivers digital item / activates VIP in database & notifies user
```

#### 1. Sending a Stars Invoice (`sendInvoice`):
```php
function send_stars_invoice(string $chatId, string $title, string $description, int $starsAmount, string $payload): array {
    return bot('sendInvoice', [
        'chat_id'      => $chatId,
        'title'        => $title,
        'description'  => $description,
        'payload'      => $payload,
        'currency'     => 'XTR', // Official Stars Currency
        // CRITICAL: provider_token is omitted entirely!
        'prices'       => [
            ['label' => $title, 'amount' => $starsAmount]
        ]
    ]);
}
```

#### 2. Handling `pre_checkout_query`:
```php
$preCheckout = $update['pre_checkout_query'] ?? null;
if ($preCheckout) {
    $queryId = $preCheckout['id'];
    $stars   = (int) $preCheckout['total_amount'];
    $payload = $preCheckout['invoice_payload'];

    // Verify inventory or conditions here
    $inStock = true;

    if ($inStock) {
        bot('answerPreCheckoutQuery', [
            'pre_checkout_query_id' => $queryId,
            'ok'                    => true
        ]);
    } else {
        bot('answerPreCheckoutQuery', [
            'pre_checkout_query_id' => $queryId,
            'ok'                    => false,
            'error_message'         => 'Sorry, this digital product is currently out of stock.'
        ]);
    }
    exit;
}
```

#### 3. Handling `successful_payment`:
```php
$msg = $update['message'] ?? null;
if ($msg && isset($msg['successful_payment'])) {
    $pay       = $msg['successful_payment'];
    $chatId    = (string) $msg['chat']['id'];
    $starsPaid = (int) $pay['total_amount'];
    $payload   = (string) $pay['invoice_payload'];
    $chargeId  = (string) $pay['telegram_payment_charge_id'];

    // Deliver product & update database
    $st = $db->prepare("INSERT INTO transactions (chat_id, stars_amount, charge_id, payload) VALUES (?, ?, ?, ?)");
    $st->execute([$chatId, $starsPaid, $chargeId, $payload]);

    bot('sendMessage', [
        'chat_id'    => $chatId,
        'text'       => "🎉 <b>Payment Successful!</b>\n\n⭐ Stars Paid: <b>{$starsPaid} XTR</b>\n🧾 Charge ID: <code>{$chargeId}</code>\n\nYour digital service has been activated immediately!",
        'parse_mode' => 'HTML'
    ]);
}
```

---

### 4.13. 🧠 AI Chat & Auto-Reply Integration (Gemini, OpenAI, Claude, OpenRouter)

Integrate state-of-the-art AI models to turn your bot into a 24/7 intelligent assistant, customer support agent, or creative writer.

#### ⚡ Key Architectural Considerations for PHP Webhooks:
1. **Synchronous Execution**: Use direct HTTP requests (cURL with 15-25s timeout) inside webhook execution.
2. **User Feedback (`sendChatAction: typing`)**: Always send typing action immediately before calling the AI API so the user sees Telegram's native "typing..." bubble.
3. **HTML Sanitization**: Always wrap user and AI text with `htmlspecialchars()` if outputting in `parse_mode: 'HTML'` to prevent malformed tag crashes.
4. **Context Memory**: Store recent conversation history in the bot's SQLite database (`storage/database.db`) so the AI remembers context across turns.

#### 🌐 Universal AI Caller Function (OpenAI / OpenRouter / Gemini Compatible):
```php
function ai_generate_reply(string $userPrompt, array $history = [], string $systemPrompt = ''): string {
    // Option A: OpenRouter / OpenAI API
    $apiKey = getenv('OPENAI_API_KEY') ?: getenv('AI_API_KEY');
    $endpoint = 'https://openrouter.ai/api/v1/chat/completions'; // Or https://api.openai.com/v1/chat/completions
    $model = 'google/gemini-2.0-flash-exp:free'; // Or gpt-4o-mini

    if (!$apiKey) {
        return "⚠️ AI API key is not configured. Please add AI_API_KEY in your .env file.";
    }

    $messages = [];
    if ($systemPrompt !== '') {
        $messages[] = ['role' => 'system', 'content' => $systemPrompt];
    }
    foreach ($history as $h) {
        $messages[] = ['role' => $h['role'], 'content' => $h['content']];
    }
    $messages[] = ['role' => 'user', 'content' => $userPrompt];

    $ch = curl_init($endpoint);
    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_POST           => true,
        CURLOPT_POSTFIELDS     => json_encode([
            'model'       => $model,
            'messages'    => $messages,
            'temperature' => 0.7,
            'max_tokens'  => 1000
        ]),
        CURLOPT_HTTPHEADER => [
            'Content-Type: application/json',
            'Authorization: Bearer ' . $apiKey
        ],
        CURLOPT_TIMEOUT => 25
    ]);
    $raw = curl_exec($ch);
    curl_close($ch);

    $json = json_decode((string)$raw, true);
    return $json['choices'][0]['message']['content'] ?? '⚠️ Sorry, I could not generate a response at this moment.';
}
```

#### 🗄️ Multi-Turn Chat History Table in SQLite:
```sql
CREATE TABLE IF NOT EXISTS chat_history (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    chat_id TEXT NOT NULL,
    role TEXT NOT NULL, -- 'user' or 'assistant'
    content TEXT NOT NULL,
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP
);
CREATE INDEX IF NOT EXISTS idx_chat_history_id ON chat_history(chat_id);
```

---

### 4.14. 📱 Telegram Mini Apps (WebApp Buttons) & Media Handlers

#### 1. Launching a Telegram Mini App from Inline Buttons:
```php
$webAppKeyboard = [
    'inline_keyboard' => [
        [
            [
                'text'    => '🚀 Open Web App',
                'web_app' => ['url' => 'https://yourdomain.com/miniapp.php'],
                'style'   => 'primary' // 🔵 Blue
            ]
        ],
        [
            [
                'text'          => '🛍️ Star Shop',
                'callback_data' => 'open_stars_shop',
                'style'         => 'success' // 🟢 Green
            ]
        ]
    ]
];

bot('sendMessage', [
    'chat_id'      => $chatId,
    'text'         => "✨ <b>Welcome to the Next-Gen Bot Studio!</b>\nLaunch the full Mini App below:",
    'parse_mode'   => 'HTML',
    'reply_markup' => json_encode($webAppKeyboard)
]);
```

#### 2. Sending Photos, Audios, and Media with Styled Buttons:
```php
bot('sendPhoto', [
    'chat_id'      => $chatId,
    'photo'        => 'https://images.unsplash.com/photo-1618005182384-a83a8bd57fbe',
    'caption'      => "🌌 <b>Digital Art NFT #104</b>\nPrice: <b>25 Stars (XTR)</b>",
    'parse_mode'   => 'HTML',
    'reply_markup' => json_encode([
        'inline_keyboard' => [
            [['text' => '⭐ Buy with Stars (25 XTR)', 'callback_data' => 'buy_art_104', 'style' => 'success']]
        ]
    ])
]);
```

---

### 4.15. 🚀 Complete Boilerplate 3: Telegram Stars Digital Store Bot

Save this as your bot's `index.php` for a complete Telegram Stars e-commerce solution:

```php
<?php
/**
 * Telegram Stars Digital Store Bot
 * Supports: Catalog, Invoices (XTR), pre_checkout_query, successful_payment, and delivery
 */
declare(strict_types=1);

@ini_set('log_errors', '1');
@ini_set('error_log', __DIR__ . '/error.log');

// 1. Load Credentials
$envFile = __DIR__ . '/.env';
$ENV = [];
if (is_file($envFile)) {
    foreach (file($envFile, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES) as $l) {
        if ($l && $l[0] !== '#' && str_contains($l, '=')) {
            [$k, $v] = explode('=', $l, 2);
            $ENV[trim($k)] = trim(trim($v), '"\'');
        }
    }
}
define('BOT_TOKEN', $ENV['BOT_TOKEN'] ?? '');
if (BOT_TOKEN === '') exit('No BOT_TOKEN');

// 2. Database
if (!is_dir(__DIR__ . '/storage')) mkdir(__DIR__ . '/storage', 0755, true);
$db = new PDO('sqlite:' . __DIR__ . '/storage/database.db', null, null, [
    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
]);
$db->exec("CREATE TABLE IF NOT EXISTS orders (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    chat_id TEXT,
    product_name TEXT,
    stars_amount INTEGER,
    charge_id TEXT,
    status TEXT DEFAULT 'completed',
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP
)");

// 3. Telegram API Helper
function bot(string $method, array $params = []): array {
    if (!defined('BOT_TOKEN') || BOT_TOKEN === '') return ['ok' => false];
    static $ch = null;
    if ($ch === null || !($ch instanceof \CurlHandle || is_resource($ch))) {
        $ch = curl_init();
    }
    $opts = [
        CURLOPT_URL            => 'https://api.telegram.org/bot' . BOT_TOKEN . '/' . $method,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_POST           => true,
        CURLOPT_POSTFIELDS     => json_encode($params, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES),
        CURLOPT_HTTPHEADER     => ['Content-Type: application/json; charset=utf-8'],
        CURLOPT_CONNECTTIMEOUT => 8,
        CURLOPT_TIMEOUT        => 15,
        CURLOPT_IPRESOLVE      => CURL_IPRESOLVE_V4,
        CURLOPT_TCP_NODELAY    => true,
        CURLOPT_DNS_CACHE_TIMEOUT => 3600,
        CURLOPT_SSL_VERIFYPEER => false,
        CURLOPT_SSL_VERIFYHOST => false,
    ];
    if (defined('CURL_HTTP_VERSION_2TLS')) {
        $opts[CURLOPT_HTTP_VERSION] = CURL_HTTP_VERSION_2TLS;
    }
    curl_setopt_array($ch, $opts);
    $res = curl_exec($ch);
    return json_decode((string)$res, true) ?: ['ok' => false];
}

// 4. Update Processing
$raw = file_get_contents('php://input');
$update = json_decode((string)$raw, true);
if (!$update) exit('Stars Bot Online');

// ── Handle Pre-Checkout Query (Within 10s) ──
if (isset($update['pre_checkout_query'])) {
    $q = $update['pre_checkout_query'];
    bot('answerPreCheckoutQuery', [
        'pre_checkout_query_id' => $q['id'],
        'ok'                    => true
    ]);
    exit;
}

// ── Handle Message & Successful Payment ──
$msg = $update['message'] ?? null;
if ($msg) {
    $chatId = (string) $msg['chat']['id'];

    // Successful Stars Payment Event
    if (isset($msg['successful_payment'])) {
        $pay      = $msg['successful_payment'];
        $stars    = (int) $pay['total_amount'];
        $chargeId = (string) $pay['telegram_payment_charge_id'];
        $payload  = (string) $pay['invoice_payload'];

        $db->prepare("INSERT INTO orders (chat_id, product_name, stars_amount, charge_id) VALUES (?, ?, ?, ?)")
           ->execute([$chatId, $payload, $stars, $chargeId]);

        bot('sendMessage', [
            'chat_id'    => $chatId,
            'text'       => "🎉 <b>Payment Confirmed!</b>\n\n⭐ Amount: <b>{$stars} Stars (XTR)</b>\n📦 Product: <b>" . htmlspecialchars($payload) . "</b>\n🧾 Charge ID: <code>{$chargeId}</code>\n\n🔑 <b>Your License Key:</b> <code>VIP-" . strtoupper(bin2hex(random_bytes(6))) . "</code>",
            'parse_mode' => 'HTML',
            'reply_markup' => json_encode([
                'inline_keyboard' => [
                    [['text' => '🛍️ Browse More Items', 'callback_data' => 'catalog', 'style' => 'primary']]
                ]
            ])
        ]);
        exit;
    }

    $text = trim($msg['text'] ?? '');
    if ($text === '/start' || $text === '/shop') {
        $catalog = [
            'inline_keyboard' => [
                [
                    ['text' => '⭐ VIP Access (50 Stars)', 'callback_data' => 'buy_vip_50', 'style' => 'success']
                ],
                [
                    ['text' => '🚀 Bot Source Code (100 Stars)', 'callback_data' => 'buy_src_100', 'style' => 'primary']
                ]
            ]
        ];

        bot('sendMessage', [
            'chat_id'      => $chatId,
            'text'         => "🌟 <b>Welcome to the Telegram Stars Digital Store!</b>\n\nPurchase digital subscriptions and goods using official Telegram Stars:\n\n• <b>VIP Membership</b>: 50 Stars\n• <b>Full Source Code</b>: 100 Stars",
            'parse_mode'   => 'HTML',
            'reply_markup' => json_encode($catalog)
        ]);
    }
}

// ── Handle Catalog Invoices via Callback Queries ──
$cb = $update['callback_query'] ?? null;
if ($cb) {
    $cbId   = $cb['id'];
    $chatId = (string) $cb['message']['chat']['id'];
    $data   = $cb['data'] ?? '';

    bot('answerCallbackQuery', ['callback_query_id' => $cbId]);

    if ($data === 'buy_vip_50') {
        bot('sendInvoice', [
            'chat_id'     => $chatId,
            'title'       => 'VIP Membership (1 Month)',
            'description' => 'Unlocks all premium features and dedicated 24/7 priority support.',
            'payload'     => 'vip_1_month',
            'currency'    => 'XTR', // Stars
            'prices'      => [
                ['label' => 'VIP 1 Month', 'amount' => 50]
            ]
        ]);
    } elseif ($data === 'buy_src_100') {
        bot('sendInvoice', [
            'chat_id'     => $chatId,
            'title'       => 'Full Bot Source Code Bundle',
            'description' => 'Complete production PHP source code with SQLite and webhook architecture.',
            'payload'     => 'bot_source_code',
            'currency'    => 'XTR', // Stars
            'prices'      => [
                ['label' => 'Source Code Bundle', 'amount' => 100]
            ]
        ]);
    }
}
```

---

### 4.16. 🚀 Complete Boilerplate 4: AI Intelligent Chatbot with SQLite Memory

Save this as your bot's `index.php` for a complete conversational AI assistant with memory:

```php
<?php
/**
 * Intelligent AI Assistant Bot with SQLite Conversation Memory
 * Compatible with OpenAI, OpenRouter, and Google Gemini
 */
declare(strict_types=1);

@ini_set('log_errors', '1');
@ini_set('error_log', __DIR__ . '/error.log');

// 1. Load Credentials from .env
$envFile = __DIR__ . '/.env';
$ENV = [];
if (is_file($envFile)) {
    foreach (file($envFile, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES) as $l) {
        if ($l && $l[0] !== '#' && str_contains($l, '=')) {
            [$k, $v] = explode('=', $l, 2);
            $ENV[trim($k)] = trim(trim($v), '"\'');
        }
    }
}
define('BOT_TOKEN', $ENV['BOT_TOKEN'] ?? '');
define('AI_API_KEY', $ENV['AI_API_KEY'] ?? ($ENV['OPENAI_API_KEY'] ?? ''));
if (BOT_TOKEN === '') exit('No BOT_TOKEN');

// 2. Database for Chat Context Memory
if (!is_dir(__DIR__ . '/storage')) mkdir(__DIR__ . '/storage', 0755, true);
$db = new PDO('sqlite:' . __DIR__ . '/storage/database.db', null, null, [
    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
]);
$db->exec("CREATE TABLE IF NOT EXISTS conversation_memory (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    chat_id TEXT NOT NULL,
    role TEXT NOT NULL,
    content TEXT NOT NULL,
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP
)");

// 3. Telegram API Helper
function bot(string $method, array $params = []): array {
    if (!defined('BOT_TOKEN') || BOT_TOKEN === '') return ['ok' => false];
    static $ch = null;
    if ($ch === null || !($ch instanceof \CurlHandle || is_resource($ch))) {
        $ch = curl_init();
    }
    $opts = [
        CURLOPT_URL            => 'https://api.telegram.org/bot' . BOT_TOKEN . '/' . $method,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_POST           => true,
        CURLOPT_POSTFIELDS     => json_encode($params, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES),
        CURLOPT_HTTPHEADER     => ['Content-Type: application/json; charset=utf-8'],
        CURLOPT_CONNECTTIMEOUT => 8,
        CURLOPT_TIMEOUT        => 15,
        CURLOPT_IPRESOLVE      => CURL_IPRESOLVE_V4,
        CURLOPT_TCP_NODELAY    => true,
        CURLOPT_DNS_CACHE_TIMEOUT => 3600,
        CURLOPT_SSL_VERIFYPEER => false,
        CURLOPT_SSL_VERIFYHOST => false,
    ];
    if (defined('CURL_HTTP_VERSION_2TLS')) {
        $opts[CURLOPT_HTTP_VERSION] = CURL_HTTP_VERSION_2TLS;
    }
    curl_setopt_array($ch, $opts);
    $res = curl_exec($ch);
    return json_decode((string)$res, true) ?: ['ok' => false];
}

// 4. AI Completion Helper
function call_ai(string $prompt, array $history): string {
    if (AI_API_KEY === '') {
        return "⚠️ AI API Key is missing! Please configure AI_API_KEY in your bot's .env file.";
    }

    $messages = [
        ['role' => 'system', 'content' => 'You are an intelligent, helpful, concise, and friendly Telegram assistant. Format your replies neatly using bold, bullet points, and code snippets when appropriate.']
    ];
    foreach ($history as $msg) {
        $messages[] = ['role' => $msg['role'], 'content' => $msg['content']];
    }
    $messages[] = ['role' => 'user', 'content' => $prompt];

    $ch = curl_init('https://openrouter.ai/api/v1/chat/completions'); // Or https://api.openai.com/v1/chat/completions
    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_POST           => true,
        CURLOPT_POSTFIELDS     => json_encode([
            'model'       => 'google/gemini-2.0-flash-exp:free', // Fast & powerful
            'messages'    => $messages,
            'temperature' => 0.7,
            'max_tokens'  => 800
        ]),
        CURLOPT_HTTPHEADER => [
            'Content-Type: application/json',
            'Authorization: Bearer ' . AI_API_KEY
        ],
        CURLOPT_TIMEOUT => 25
    ]);
    $res = curl_exec($ch);
    curl_close($ch);

    $json = json_decode((string)$res, true);
    return $json['choices'][0]['message']['content'] ?? '⚠️ Sorry, I could not generate an answer right now.';
}

// 5. Update Processing
$raw = file_get_contents('php://input');
$update = json_decode((string)$raw, true);
if (!$update) exit('AI Bot Online');

$msg = $update['message'] ?? null;
if ($msg && isset($msg['text'])) {
    $chatId = (string) $msg['chat']['id'];
    $text   = trim($msg['text']);

    if ($text === '/start') {
        $menu = [
            'inline_keyboard' => [
                [
                    ['text' => '🧹 Clear Chat Memory', 'callback_data' => 'clear_memory', 'style' => 'danger'],
                    ['text' => 'ℹ️ About Assistant', 'callback_data' => 'about_ai', 'style' => 'primary']
                ]
            ]
        ];

        bot('sendMessage', [
            'chat_id'      => $chatId,
            'text'         => "🤖 <b>Hello! I am your AI Assistant.</b>\n\nAsk me any question, brainstorm ideas, request code, or chat about anything! I remember our conversation context automatically.",
            'parse_mode'   => 'HTML',
            'reply_markup' => json_encode($menu)
        ]);
        exit;
    }

    if ($text === '/clear') {
        $db->prepare("DELETE FROM conversation_memory WHERE chat_id = ?")->execute([$chatId]);
        bot('sendMessage', ['chat_id' => $chatId, 'text' => '🧹 <b>Conversation memory cleared!</b>', 'parse_mode' => 'HTML']);
        exit;
    }

    // 1. Show Typing Status to User
    bot('sendChatAction', ['chat_id' => $chatId, 'action' => 'typing']);

    // 2. Retrieve Last 6 Conversation Turns for Memory
    $st = $db->prepare("SELECT role, content FROM conversation_memory WHERE chat_id = ? ORDER BY id DESC LIMIT 6");
    $st->execute([$chatId]);
    $history = array_reverse($st->fetchAll());

    // 3. Call AI
    $aiResponse = call_ai($text, $history);

    // 4. Save User Prompt and AI Reply to Memory
    $ins = $db->prepare("INSERT INTO conversation_memory (chat_id, role, content) VALUES (?, ?, ?)");
    $ins->execute([$chatId, 'user', $text]);
    $ins->execute([$chatId, 'assistant', $aiResponse]);

    // 5. Deliver Reply
    bot('sendMessage', [
        'chat_id'    => $chatId,
        'text'       => $aiResponse,
        'reply_markup' => json_encode([
            'inline_keyboard' => [
                [['text' => '🧹 Reset Context', 'callback_data' => 'clear_memory', 'style' => 'danger']]
            ]
        ])
    ]);
}

$cb = $update['callback_query'] ?? null;
if ($cb) {
    $cbId   = $cb['id'];
    $chatId = (string) $cb['message']['chat']['id'];
    $data   = $cb['data'] ?? '';

    if ($data === 'clear_memory') {
        $db->prepare("DELETE FROM conversation_memory WHERE chat_id = ?")->execute([$chatId]);
        bot('answerCallbackQuery', ['callback_query_id' => $cbId, 'text' => 'Context Memory Cleared!']);
        bot('sendMessage', ['chat_id' => $chatId, 'text' => '🧹 <b>Conversation context reset. What would you like to discuss next?</b>', 'parse_mode' => 'HTML']);
    } elseif ($data === 'about_ai') {
        bot('answerCallbackQuery', ['callback_query_id' => $cbId]);
        bot('sendMessage', [
            'chat_id'    => $chatId,
            'text'       => "🧠 <b>AI Assistant Specifications:</b>\n\n• Multi-turn SQLite memory cache\n• Styled inline action buttons\n• Supports OpenAI, OpenRouter, and Google Gemini models",
            'parse_mode' => 'HTML'
        ]);
    }
}
```

---

### 4.17. 💥 Message Reactions & Emoji Reacts (`setMessageReaction`)

Bots can react to messages with standard Unicode emojis or Custom Emojis, featuring optional full-screen "big" animations!

#### 📌 API Method: `setMessageReaction`

##### Parameters:
- `chat_id`: Target chat ID or `@channelusername`
- `message_id`: Message ID to react to
- `reaction`: Array of `ReactionType` objects (up to 1 reaction per bot per message)
- `is_big`: *(Optional)* Boolean (`true` displays full-screen popping animation!)

#### 💡 Helper Function for Sending Reactions:
```php
function bot_react(string|int $chatId, int $messageId, string $emoji = '👍', bool $isBig = true): array {
    return bot('setMessageReaction', [
        'chat_id'    => $chatId,
        'message_id' => $messageId,
        'reaction'   => [
            [
                'type'  => 'emoji',
                'emoji' => $emoji
            ]
        ],
        'is_big'     => $isBig
    ]);
}

// React with a Custom Emoji:
function bot_react_custom(string|int $chatId, int $messageId, string $customEmojiId, bool $isBig = true): array {
    return bot('setMessageReaction', [
        'chat_id'    => $chatId,
        'message_id' => $messageId,
        'reaction'   => [
            [
                'type'            => 'custom_emoji',
                'custom_emoji_id' => $customEmojiId
            ]
        ],
        'is_big'     => $isBig
    ]);
}
```

#### ⚡ Practical Usage in Webhook Handler:
```php
$msg = $update['message'] ?? null;
if ($msg && isset($msg['text'])) {
    $chatId = $msg['chat']['id'];
    $msgId  = $msg['message_id'];
    $text   = trim($msg['text']);

    // Instantly celebrate when user submits a successful command
    if ($text === '/success' || $text === 'paid') {
        bot_react($chatId, $msgId, '🎉', true); // Big celebration animation!
    } elseif ($text === '/like') {
        bot_react($chatId, $msgId, '🔥', false);
    }
}
```

#### 🔄 Handling Incoming Reaction Updates:
Telegram notifies your bot whenever users react to messages via two updates:
```php
// Individual user reaction event
$userReaction = $update['message_reaction'] ?? null;
if ($userReaction) {
    $chatId   = $userReaction['chat']['id'];
    $msgId    = $userReaction['message_id'];
    $user     = $userReaction['user'] ?? [];
    $newReact = $userReaction['new_reaction'] ?? []; // List of newly placed reactions
}

// Aggregate reaction counts (useful for channels)
$reactionCount = $update['message_reaction_count'] ?? null;
if ($reactionCount) {
    $chatId = $reactionCount['chat']['id'];
    $counts = $reactionCount['reactions']; // List of ReactionCount objects
}
```

---

### 4.18. 🔒 Paid Media with Telegram Stars (`sendPaidMedia`)

Monetize exclusive content (photos, albums, and video courses) by locking them behind Telegram Stars. Users pay Stars directly in chat to unlock and view the media!

#### 📌 Method: `sendPaidMedia`
```php
function send_paid_photo(string|int $chatId, int $starCount, string $photoUrl, string $caption): array {
    return bot('sendPaidMedia', [
        'chat_id'    => $chatId,
        'star_count' => $starCount, // Stars required to unlock (1 - 25,000)
        'media'      => [
            [
                'type'  => 'photo',
                'media' => $photoUrl
            ]
        ],
        'caption'    => $caption,
        'parse_mode' => 'HTML'
    ]);
}

// Example: Lock an exclusive digital download
send_paid_photo($chatId, 15, 'https://images.unsplash.com/photo-1618005182384-a83a8bd57fbe', "🔒 <b>Exclusive 4K Wallpaper Pack</b>\nUnlock now for only <b>15 Stars!</b>");
```

---

### 4.19. 💼 Telegram Business Integration (`business_connection`, `business_message`)

Telegram Business allows regular users and brands to connect your bot to their personal or business accounts to act as a 24/7 AI receptionist, order taker, or CRM auto-responder.

#### 🔄 1. Handling Business Connections (`business_connection`):
```php
$bizConn = $update['business_connection'] ?? null;
if ($bizConn) {
    $connId   = $bizConn['id'];
    $userChat = $bizConn['user_chat_id'];
    $rights   = $bizConn['rights'] ?? [];
    $canReply = !empty($rights['can_reply']);

    // Store connection in SQLite
    $st = $db->prepare("INSERT OR REPLACE INTO business_connections (connection_id, user_chat_id, can_reply) VALUES (?, ?, ?)");
    $st->execute([$connId, $userChat, $canReply ? 1 : 0]);
    exit;
}
```

#### 💬 2. Answering Messages on Behalf of Business (`business_message`):
```php
$bizMsg = $update['business_message'] ?? null;
if ($bizMsg) {
    $connId = $bizMsg['business_connection_id'];
    $chatId = $bizMsg['chat']['id'];
    $text   = trim($bizMsg['text'] ?? '');

    // Reply seamlessly on behalf of the business account
    bot('sendMessage', [
        'business_connection_id' => $connId,
        'chat_id'                => $chatId,
        'text'                   => "👋 Hello! Thank you for reaching out to our business. How may we assist you today?",
        'parse_mode'             => 'HTML'
    ]);
    exit;
}
```

---

### 4.20. 🎁 Telegram Star Gifts System (`sendGift`)

Send official Telegram virtual gifts to users or channels directly from your bot's Stars balance.

```php
function send_telegram_gift(int $userId, string $giftId, string $message = '', bool $payUpgrade = false): array {
    return bot('sendGift', [
        'user_id'          => $userId,
        'gift_id'          => $giftId,
        'text'             => $message,
        'pay_for_upgrade'  => $payUpgrade // Bot pays upgrade fee if true
    ]);
}
```

---

### 4.21. 🏛️ Forum Topics Management (`createForumTopic`, `message_thread_id`)

In supergroups with topics enabled, bots can create, rename, and manage threads, directing communications into dedicated rooms.

#### 1. Creating a Forum Topic:
```php
function create_bot_topic(string|int $chatId, string $topicName, string $customEmojiId = ''): array {
    $params = [
        'chat_id' => $chatId,
        'name'    => $topicName
    ];
    if ($customEmojiId !== '') {
        $params['icon_custom_emoji_id'] = $customEmojiId;
    }
    return bot('createForumTopic', $params);
}
```

#### 2. Sending Messages Directly to a Topic (`message_thread_id`):
```php
bot('sendMessage', [
    'chat_id'           => $supergroupId,
    'message_thread_id' => $topicId, // Directs message to specific topic
    'text'              => "📢 <b>Support Ticket #492 Opened</b>\nA customer is waiting for assistance.",
    'parse_mode'        => 'HTML'
]);
```

---

### 4.22. 👥 Chat Join Requests & Auto-Approvals (`approveChatJoinRequest`)

For private channels and VIP groups requiring approval to join, your bot can automatically approve or decline members based on subscription status or payment verification.

```php
$joinReq = $update['chat_join_request'] ?? null;
if ($joinReq) {
    $chatId = $joinReq['chat']['id'];
    $userId = $joinReq['from']['id'];
    $invite = $joinReq['invite_link']['invite_link'] ?? '';

    // Verify condition (e.g. user paid Stars or registered in DB)
    $approved = true;

    if ($approved) {
        bot('approveChatJoinRequest', [
            'chat_id' => $chatId,
            'user_id' => $userId
        ]);

        // Send a private welcome message
        bot('sendMessage', [
            'chat_id'    => $userId,
            'text'       => "🎉 <b>Welcome to the VIP Channel!</b>\nYour membership request has been automatically approved.",
            'parse_mode' => 'HTML'
        ]);
    } else {
        bot('declineChatJoinRequest', [
            'chat_id' => $chatId,
            'user_id' => $userId
        ]);
    }
    exit;
}
```

---

### 4.23. ⚡ Inline Mode Queries & Instant Results (`answerInlineQuery`)

Allow users to type `@YourBot query` in any private chat, group, or channel to summon interactive results directly.

```php
$inlineQuery = $update['inline_query'] ?? null;
if ($inlineQuery) {
    $queryId = $inlineQuery['id'];
    $query   = trim($inlineQuery['query']);

    $results = [
        [
            'type'        => 'article',
            'id'          => 'result_1',
            'title'       => '🌟 Botlify Clouding Platform',
            'description' => 'Deploy high-performance PHP Telegram bots in seconds',
            'input_message_content' => [
                'message_text' => "🚀 <b>Botlify Cloud</b>\nHost your bots with SQLite, Crons, and Webhooks for free!\nhttps://digibd.store",
                'parse_mode'   => 'HTML'
            ]
        ],
        [
            'type'        => 'article',
            'id'          => 'result_2',
            'title'       => '⭐ Telegram Stars Store',
            'description' => 'Pay with Telegram Stars (XTR)',
            'input_message_content' => [
                'message_text' => "⭐ Check out our official Telegram Stars digital shop!",
                'parse_mode'   => 'HTML'
            ]
        ]
    ];

    bot('answerInlineQuery', [
        'inline_query_id' => $queryId,
        'results'         => json_encode($results),
        'cache_time'      => 300,
        'is_personal'     => true
    ]);
    exit;
}
```

---

### 4.24. 🎲 Interactive Entertainment: Polls, Quizzes & Animated Dice (`sendDice`, `sendPoll`)

#### 1. Animated Physics Dice (`sendDice`):
```php
// Supports: '🎲' (Dice), '🎯' (Darts), '🏀' (Basketball), '⚽' (Football), '🎳' (Bowling), '🎰' (Slot Machine)
bot('sendDice', [
    'chat_id' => $chatId,
    'emoji'   => '🎰'
]);
```

#### 2. Quizzes and Polls (`sendPoll`):
```php
bot('sendPoll', [
    'chat_id'               => $chatId,
    'question'              => 'Which currency is used for official Telegram bot payments?',
    'options'               => json_encode(['USD ($)', 'Telegram Stars (XTR)', 'Bitcoin (BTC)']),
    'is_anonymous'          => false,
    'type'                  => 'quiz',
    'correct_option_id'     => 1, // 'Telegram Stars (XTR)'
    'explanation'           => 'Telegram Stars (XTR) is the official in-app currency for digital goods in Telegram bots.',
    'explanation_parse_mode'=> 'HTML'
]);
```

---

### 4.25. 🛡️ Production Webhook Security & Dropping Pending Updates

#### 1. Setting Up Webhook with Secret Token & Clean Slate:
```php
function setup_bot_webhook(string $botToken, string $webhookUrl, string $secretToken): array {
    $url = "https://api.telegram.org/bot{$botToken}/setWebhook";
    $ch = curl_init($url);
    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_POST           => true,
        CURLOPT_POSTFIELDS     => json_encode([
            'url'                  => $webhookUrl,
            'secret_token'         => $secretToken, // 1 - 256 characters (a-z, A-Z, 0-9, _, -)
            'drop_pending_updates' => true,         // Ignores stale pending requests on startup
            'allowed_updates'      => [
                'message', 'edited_message', 'callback_query', 'inline_query',
                'pre_checkout_query', 'successful_payment', 'message_reaction',
                'message_reaction_count', 'chat_join_request', 'business_connection',
                'business_message'
            ]
        ]),
        CURLOPT_HTTPHEADER     => ['Content-Type: application/json']
    ]);
    $res = curl_exec($ch);
    curl_close($ch);
    return json_decode((string)$res, true) ?: [];
}
```

#### 2. Verifying Secret Token Inside `index.php`:
```php
// Add this at the very top of your index.php for unbreakable webhook verification:
$receivedSecret = $_SERVER['HTTP_X_TELEGRAM_BOT_API_SECRET_TOKEN'] ?? '';
$expectedSecret = $ENV['WEBHOOK_SECRET'] ?? '';

if ($expectedSecret !== '' && !hash_equals($expectedSecret, $receivedSecret)) {
    http_response_code(403);
    exit('Forbidden: Invalid webhook secret token.');
}
```

---

### 4.26. 🔘 Bot Commands, Scopes & Native Menu Button (`setMyCommands`, `setChatMenuButton`)

Telegram bots have a native **[Menu] button** at the bottom-left corner of the chat input bar. Configuring slash commands and the Menu Button creates an elite UX where users can discover features in 1 tap without typing `/`.

---

#### 1. Registering Slash Commands with Scopes (`setMyCommands`)

Commands appear in the autocomplete popup when typing `/` and in the native Telegram Menu Sheet. Always organize commands by **Scopes** so regular users see customer commands while bot owners see administrative controls.

```php
function register_bot_commands(?string $adminChatId = null): array {
    $results = [];

    // A. Public User Commands (Visible to all users in private chats)
    $results['users'] = bot('setMyCommands', [
        'commands' => [
            ['command' => 'start',    'description' => '🚀 Launch main dashboard & keyboard'],
            ['command' => 'menu',     'description' => '📋 Open interactive feature menu'],
            ['command' => 'balance',  'description' => '💳 Check wallet & referral earnings'],
            ['command' => 'bonus',    'description' => '🎁 Claim daily bonus reward'],
            ['command' => 'help',     'description' => 'ℹ️ Usage guide & customer support'],
            ['command' => 'settings', 'description' => '⚙️ Manage preferences & notifications']
        ],
        'scope' => ['type' => 'all_private_chats']
    ]);

    // B. Secret Admin Commands (Visible ONLY to the bot admin/owner)
    if ($adminChatId && preg_match('/^-?\d+$/', (string)$adminChatId)) {
        $results['admin'] = bot('setMyCommands', [
            'commands' => [
                ['command' => 'start',     'description' => '🚀 Launch main dashboard'],
                ['command' => 'admin',     'description' => '👑 Open Admin Control Panel'],
                ['command' => 'broadcast', 'description' => '📢 Send mass broadcast to users'],
                ['command' => 'stats',     'description' => '📊 Live platform analytics & KPIs'],
                ['command' => 'users',     'description' => '👥 User management & search']
            ],
            'scope' => ['type' => 'chat', 'chat_id' => (int)$adminChatId]
        ]);
    }

    return $results;
}
```

---

#### 2. Customizing the Native Bottom-Left Menu Button (`setChatMenuButton`)

The `setChatMenuButton` method controls what happens when the user clicks the native `[Menu]` button next to the message input box:

##### Option A: Native Commands Menu Sheet (Recommended for Bots)
Opens the native Telegram popup sheet listing all registered slash commands with their descriptive icons:
```php
function set_native_commands_menu(?string $chatId = null): array {
    $params = [
        'menu_button' => [
            'type' => 'commands' // 📋 Opens native command sheet
        ]
    ];
    if ($chatId !== null) {
        $params['chat_id'] = $chatId;
    }
    return bot('setChatMenuButton', $params);
}
```

##### Option B: Telegram Mini App / WebApp Menu Button
Turns the `[Menu]` button into an instant Mini App launcher:
```php
function set_webapp_menu_button(string $chatId, string $webAppUrl, string $buttonText = '🚀 Open App'): array {
    return bot('setChatMenuButton', [
        'chat_id'     => $chatId,
        'menu_button' => [
            'type'    => 'web_app',
            'text'    => $buttonText,
            'web_app' => ['url' => $webAppUrl]
        ]
    ]);
}
```

##### Option C: Reset to Default Menu Button
```php
function reset_menu_button(?string $chatId = null): array {
    $params = ['menu_button' => ['type' => 'default']];
    if ($chatId !== null) $params['chat_id'] = $chatId;
    return bot('setChatMenuButton', $params);
}
```

---

#### 3. Production Auto-Setup Pattern (Zero Webhook Latency)

Never call `setMyCommands` on every incoming webhook update—that wastes CPU and hits Telegram API rate limits. Instead, use an automatic one-time lock file or database flag:

```php
// Auto-configure commands and menu button once on first run or update
function ensure_bot_menu_configured(): void {
    $lockFile = __DIR__ . '/.menu_configured';
    if (!is_file($lockFile)) {
        // 1. Register Public Commands
        register_bot_commands(defined('ADMIN_CHAT_ID') ? (string)ADMIN_CHAT_ID : null);

        // 2. Configure Native [Menu] Button
        set_native_commands_menu();

        // 3. Save lock file so it runs only once
        @file_put_contents($lockFile, date('Y-m-d H:i:s'));
    }
}

// Call at the start of index.php after loading .env
ensure_bot_menu_configured();
```

---

#### 4. Responding to Slash Commands in `index.php`

When a user taps a command from the Menu button or types `/balance`, handle it seamlessly in your update dispatcher:

```php
$text = trim($message['text'] ?? '');

switch ($text) {
    case '/start':
        send_welcome_dashboard($chatId);
        break;

    case '/menu':
        send_feature_grid($chatId);
        break;

    case '/balance':
        send_wallet_overview($chatId);
        break;

    case '/admin':
        if ((string)$chatId === (string)ADMIN_CHAT_ID) {
            send_admin_panel($chatId);
        } else {
            bot('sendMessage', ['chat_id' => $chatId, 'text' => '⛔ Access denied.']);
        }
        break;
}
```

---

### 4.27. 📝 Bot Profile, Descriptions & Multilingual Onboarding (`setMyDescription`, `setMyName`)

Automate how your bot appears across Telegram search results, profile dialogs, and empty chat screens.

```php
// 1. Set Chat Placeholder Description (0 - 512 chars, shown before user taps /start)
bot('setMyDescription', [
    'description'   => "🤖 Welcome to the Official Botlify Cloud Assistant!\n\nBuild, host, and scale Telegram bots with integrated SQLite, Cron jobs, Telegram Stars payments, and AI intelligence.",
    'language_code' => ''
]);

// 2. Set Short Description (0 - 120 chars, displayed on bot profile page and shared links)
bot('setMyShortDescription', [
    'short_description' => 'Deploy Telegram bots with SQLite, Stars Pay, and AI.',
    'language_code'     => ''
]);

// 3. Set Bot Name in Title Bar
bot('setMyName', [
    'name'          => 'Smart Bot Studio 🚀',
    'language_code' => ''
]);
```

---

### 4.28. 👥 Chat Member & Admin Rights Management (`banChatMember`, `restrictChatMember`, `promoteChatMember`)

Automate community moderation, gatekeep channels, and restrict disruptive users.

#### 1. Banning / Kicking Members (`banChatMember`):
```php
function ban_user(string|int $chatId, int $userId, int $banDurationSeconds = 0): array {
    return bot('banChatMember', [
        'chat_id'         => $chatId,
        'user_id'         => $userId,
        'until_date'      => $banDurationSeconds > 0 ? time() + $banDurationSeconds : 0, // 0 = permanent
        'revoke_messages' => true // Deletes recent messages from the banned user
    ]);
}

// Unban / un-mute:
bot('unbanChatMember', ['chat_id' => $chatId, 'user_id' => $userId, 'only_if_banned' => true]);
```

#### 2. Restricting Permissions (`restrictChatMember` - Muting):
```php
function mute_user(string|int $chatId, int $userId, int $muteSeconds = 3600): array {
    return bot('restrictChatMember', [
        'chat_id'     => $chatId,
        'user_id'     => $userId,
        'until_date'  => time() + $muteSeconds,
        'permissions' => [
            'can_send_messages'         => false,
            'can_send_media_messages'   => false,
            'can_send_polls'            => false,
            'can_send_other_messages'   => false,
            'can_add_web_page_previews' => false
        ]
    ]);
}
```

#### 3. Promoting Members & Setting Custom Admin Titles:
```php
bot('promoteChatMember', [
    'chat_id'              => $chatId,
    'user_id'              => $userId,
    'can_manage_chat'      => true,
    'can_delete_messages'  => true,
    'can_invite_users'     => true,
    'can_pin_messages'     => true,
    'can_manage_topics'    => true
]);

// Set Custom Title Badge (e.g. "👑 Co-Founder" or "🛡️ Moderator")
bot('setChatAdministratorCustomTitle', [
    'chat_id'      => $chatId,
    'user_id'      => $userId,
    'custom_title' => '🛡️ Senior Mod'
]);
```

---

### 4.29. 📌 Chat Settings, Pinned Messages & Batch Deletions (`deleteMessages`, `pinChatMessage`, `copyMessages`)

#### 1. Batch Deleting Messages (`deleteMessages`):
Delete up to 100 messages simultaneously in a single API roundtrip:
```php
function batch_delete_messages(string|int $chatId, array $messageIds): array {
    return bot('deleteMessages', [
        'chat_id'     => $chatId,
        'message_ids' => $messageIds // Array of integers [101, 102, 103, ...]
    ]);
}
```

#### 2. Batch Copying & Forwarding Messages (`copyMessages`, `forwardMessages`):
Replicate content across chats without forwarding link headers:
```php
bot('copyMessages', [
    'chat_id'      => $destinationChatId,
    'from_chat_id' => $sourceChatId,
    'message_ids'  => [201, 202, 203]
]);
```

#### 3. Pinning and Unpinning Messages:
```php
// Pin message silently or with notification
bot('pinChatMessage', [
    'chat_id'              => $chatId,
    'message_id'           => $messageId,
    'disable_notification' => false
]);

// Unpin all messages
bot('unpinAllChatMessages', ['chat_id' => $chatId]);
```

---

### 4.30. 🚀 Channel Boosts & User Boost Detection (`getUserChatBoosts`, `chat_boost`)

Reward users who boost your Telegram Channel or Supergroup with automatic VIP membership and exclusive perks!

#### 1. Checking If a User Boosted Your Channel:
```php
function check_user_boosts(string|int $channelChatId, int $userId): array {
    $res = bot('getUserChatBoosts', [
        'chat_id' => $channelChatId,
        'user_id' => $userId
    ]);

    $boosts = $res['result']['boosts'] ?? [];
    return [
        'is_booster'  => count($boosts) > 0,
        'boost_count' => count($boosts),
        'boosts'      => $boosts
    ];
}
```

#### 2. Real-Time Boost Event Handlers:
```php
// User added a boost
$boostEvent = $update['chat_boost'] ?? null;
if ($boostEvent) {
    $chatId = $boostEvent['chat']['id'];
    $user   = $boostEvent['boost']['source']['user'] ?? [];
    $userId = $user['id'] ?? 0;

    // Credit VIP reward in SQLite
    $db->prepare("UPDATE users SET is_vip = 1 WHERE chat_id = ?")->execute([$userId]);
}

// User removed a boost
$removedBoost = $update['removed_chat_boost'] ?? null;
if ($removedBoost) {
    $userId = $removedBoost['source']['user']['id'] ?? 0;
    // Downgrade status if desired
}
```

---

### 4.31. 🖼️ Media Albums & Groups (`sendMediaGroup`)

Deliver between 2 and 10 photos or videos together in an aesthetically cohesive album grid:

```php
function send_product_album(string|int $chatId, array $photoUrls, string $caption): array {
    $media = [];
    foreach ($photoUrls as $idx => $url) {
        $item = [
            'type'  => 'photo',
            'media' => $url
        ];
        if ($idx === 0) {
            $item['caption']    = $caption;
            $item['parse_mode'] = 'HTML';
        }
        $media[] = $item;
    }

    return bot('sendMediaGroup', [
        'chat_id' => $chatId,
        'media'   => json_encode($media)
    ]);
}

// Example usage:
send_product_album($chatId, [
    'https://images.unsplash.com/photo-1550745165-9bc0b252726f',
    'https://images.unsplash.com/photo-1518770660439-4636190af475'
], "📸 <b>Hardware Showcase Album</b>\nExplore our latest server infrastructure.");
```

---

### 4.32. 📍 Geolocation, Live Location & Venues (`sendLocation`, `editMessageLiveLocation`)

Build delivery trackers, event guides, and location-based check-ins.

#### 1. Static Location Pin:
```php
bot('sendLocation', [
    'chat_id'   => $chatId,
    'latitude'  => 23.8103, // Latitude
    'longitude' => 90.4125  // Longitude
]);
```

#### 2. Live Location Sharing (Real-Time Driver / Delivery Tracking):
```php
// Initiate Live Location (updates for up to 24 hours / 86400s)
$liveMsg = bot('sendLocation', [
    'chat_id'     => $chatId,
    'latitude'    => 23.8103,
    'longitude'   => 90.4125,
    'live_period' => 3600 // Active for 1 hour
]);
$msgId = $liveMsg['result']['message_id'] ?? 0;

// Dynamically update coordinates as user moves:
bot('editMessageLiveLocation', [
    'chat_id'    => $chatId,
    'message_id' => $msgId,
    'latitude'   => 23.8150,
    'longitude'  => 90.4200
]);

// Stop live tracking when order delivered:
bot('stopMessageLiveLocation', ['chat_id' => $chatId, 'message_id' => $msgId]);
```

---

### 4.33. 📱 Contacts, Phone Verification & VCards (`request_contact`, `sendContact`)

Securely verify genuine user identities and cell phone numbers using Telegram's native contact prompt:

```php
// 1. Prompt User to Share Verified Phone Number
$keyboard = [
    'keyboard' => [
        [
            ['text' => '📱 Share Verified Phone Number', 'request_contact' => true]
        ]
    ],
    'resize_keyboard'  => true,
    'one_time_keyboard'=> true
];

bot('sendMessage', [
    'chat_id'      => $chatId,
    'text'         => "🔐 <b>Account Verification Required</b>\nPlease tap the button below to share your verified Telegram phone number:",
    'parse_mode'   => 'HTML',
    'reply_markup' => json_encode($keyboard)
]);

// 2. Intercept Verified Contact in Webhook Handler:
$contact = $update['message']['contact'] ?? null;
if ($contact) {
    $phoneNumber = $contact['phone_number'];
    $userId      = $contact['user_id'];

    // Verify user didn't spoof another person's vCard
    if ((string)$userId === (string)$update['message']['from']['id']) {
        // Save verified number in SQLite
        $db->prepare("UPDATE users SET phone = ?, is_verified = 1 WHERE chat_id = ?")->execute([$phoneNumber, $userId]);
        
        bot('sendMessage', [
            'chat_id'      => $userId,
            'text'         => "✅ <b>Phone Verified!</b>\nNumber: <code>{$phoneNumber}</code>\nYour account is now fully unlocked.",
            'parse_mode'   => 'HTML',
            'reply_markup' => json_encode(['remove_keyboard' => true])
        ]);
    }
}
```

---

### 4.34. 🎨 Custom Sticker Packs & Stickers (`createNewStickerSet`, `sendSticker`)

Deploy branded sticker collections and send stickers in response to user milestones:

```php
// 1. Send an animated or static sticker
bot('sendSticker', [
    'chat_id' => $chatId,
    'sticker' => 'CAACAgIAAxkBAAE...sticker_file_id'
]);

// 2. Programmatically Create a Bot Sticker Set:
bot('createNewStickerSet', [
    'user_id'        => $ownerUserId,
    'name'           => 'my_bot_pack_by_' . BOT_USERNAME, // Must end in _by_<bot_username>
    'title'          => 'VIP Community Pack',
    'sticker_format' => 'static', // 'static' (PNG/WEBP), 'animated' (TGS), 'video' (WEBM)
    'stickers'       => [
        [
            'sticker'    => 'https://example.com/sticker1.png',
            'emoji_list' => ['🚀', '⭐'],
            'format'     => 'static'
        ]
    ]
]);
```

---

### 4.35. 🎙️ Voice Notes, Audio & Circular Video Notes (`sendVoice`, `sendVideoNote`, `sendAudio`)

Deliver rich auditory and circular video experiences:

```php
// 1. Send Circular Video Note (Telescope message)
bot('sendVideoNote', [
    'chat_id'    => $chatId,
    'video_note' => 'https://example.com/camera_bubble.mp4',
    'length'     => 360 // Diameter in pixels
]);

// 2. Send Voice Memo with Caption & Waveform
bot('sendVoice', [
    'chat_id'  => $chatId,
    'voice'    => 'https://example.com/audio_memo.ogg',
    'caption'  => '🎙️ <b>Daily Podcast Briefing</b>',
    'parse_mode' => 'HTML',
    'duration' => 45
]);

// 3. Send MP3 Audio File with Artist & Title metadata:
bot('sendAudio', [
    'chat_id'   => $chatId,
    'audio'     => 'https://example.com/track.mp3',
    'performer' => 'Smart Host Audio',
    'title'     => 'Welcome Jingle',
    'duration'  => 120
]);
```

---

### 4.36. 📢 Mandatory Channel Force-Subscribe / Force Join System (`getChatMember`)

Force Subscription (Force Join / Force Sub) is the #1 viral growth mechanic for Telegram bots. Before a user can interact with any bot feature, the bot checks if they have joined your required sponsor channels or community groups.

> **⚠️ Prerequisites:** The bot MUST be added as an **Administrator** in your target channel/group so it has permission to call `getChatMember`.

---

#### 1. The Membership Verifier Helper (`is_channel_member`)
```php
function is_channel_member(string|int $userId, string|int $channelId): bool {
    $res = bot('getChatMember', [
        'chat_id' => $channelId,
        'user_id' => $userId
    ]);
    if (empty($res['ok'])) {
        return false;
    }
    $status = $res['result']['status'] ?? '';
    // User is a valid subscriber if status is creator, admin, member, or restricted
    return in_array($status, ['creator', 'administrator', 'member', 'restricted'], true);
}
```

---

#### 2. Multi-Channel Force Subscribe Engine
Define your sponsor channels or official groups in an array:
```php
$REQUIRED_CHANNELS = [
    [
        'id'   => '@MyOfficialChannel',        // Public username with @ OR numeric chat ID -100...
        'name' => 'Official Announcements',
        'url'  => 'https://t.me/MyOfficialChannel'
    ],
    [
        'id'   => '-1002345678901',           // Private channel ID (bot must be admin)
        'name' => 'VIP Community Chat',
        'url'  => 'https://t.me/+AbCdEfGhIjKlMnOp'
    ]
];

function get_unjoined_channels(string|int $userId, array $channels): array {
    $missing = [];
    foreach ($channels as $ch) {
        if (!is_channel_member($userId, $ch['id'])) {
            $missing[] = $ch;
        }
    }
    return $missing;
}
```

---

#### 3. Displaying the Modern Styled Lock Screen
When an unjoined user tries to use the bot, lock their screen with styled URL buttons and an interactive **✅ Joined! Check Now** callback button:

```php
function send_force_sub_prompt(string|int $chatId, array $unjoinedChannels): array {
    $keyboard = [];
    foreach ($unjoinedChannels as $idx => $ch) {
        $keyboard[] = [
            ['text' => '📢 Join ' . $ch['name'], 'url' => $ch['url']]
        ];
    }
    // Telegram 8.0 styled success button for verification
    $keyboard[] = [
        ['text' => '✅ Joined! Check Now', 'callback_data' => 'btn_verify_sub', 'style' => 'success']
    ];

    $text = "🔒 <b>Access Restricted!</b>\n\n"
          . "To use this bot, you must be a member of our official channels below.\n\n"
          . "👉 Please join all channels and tap <b>Joined! Check Now</b> to unlock access.";

    return bot('sendMessage', [
        'chat_id'                  => $chatId,
        'text'                     => $text,
        'parse_mode'               => 'HTML',
        'disable_web_page_preview' => true,
        'reply_markup'             => ['inline_keyboard' => $keyboard]
    ]);
}
```

---

#### 4. Handling the Verification Callback in `index.php`
When the user taps the verification button, dismiss the loading spinner immediately with `answerCallbackQuery`. If they've joined, delete the lock message and show the main menu; otherwise, show a friendly Telegram alert modal!

```php
// Inside your update dispatcher:
if ($cb) {
    $cbId   = (string)$cb['id'];
    $data   = (string)($cb['data'] ?? '');
    $userId = (string)$cb['from']['id'];
    $chatId = (string)$cb['message']['chat']['id'];
    $msgId  = (int)$cb['message']['message_id'];

    if ($data === 'btn_verify_sub') {
        $unjoined = get_unjoined_channels($userId, $REQUIRED_CHANNELS);
        if (empty($unjoined)) {
            // Success! Dismiss spinner with celebration
            bot('answerCallbackQuery', [
                'callback_query_id' => $cbId,
                'text'              => '🎉 Access unlocked! Welcome aboard!',
                'show_alert'        => false
            ]);
            // Remove the lock prompt
            bot('deleteMessage', ['chat_id' => $chatId, 'message_id' => $msgId]);
            // Send celebration reaction
            bot('setMessageReaction', [
                'chat_id'    => $chatId,
                'message_id' => $msgId,
                'reaction'   => [['type' => 'emoji', 'emoji' => '🎉']]
            ]);
            // Deliver Main Menu
            send_welcome_menu($chatId);
        } else {
            // Still missing channels - show native popup alert
            bot('answerCallbackQuery', [
                'callback_query_id' => $cbId,
                'text'              => "⚠️ You have not joined all channels yet!\n\nPlease join all required channels and try again.",
                'show_alert'        => true
            ]);
        }
        exit;
    }
}

// In Message Handler (/start or any command):
if ($msg && isset($msg['text'])) {
    $userId = (string)$msg['from']['id'];
    $chatId = (string)$msg['chat']['id'];

    // Enforce channel membership before processing ANY command
    $unjoined = get_unjoined_channels($userId, $REQUIRED_CHANNELS);
    if (!empty($unjoined)) {
        send_force_sub_prompt($chatId, $unjoined);
        exit;
    }

    // Proceed to normal bot logic...
}
```

---

### 4.37. 🎆 Full-Screen Message Effects (`message_effect_id`)

Telegram Bot API 8.0 allows bots to trigger **full-screen animated background effects** when sending messages in private chats! When the user opens the message, vivid animations (such as bursting confetti or blazing fire) erupt across their entire screen.

#### Common Telegram Effect IDs:
| Effect Name | Emoji | `message_effect_id` String |
| :--- | :---: | :--- |
| **Confetti / Celebration** | 🎉 | `5046509860389126442` |
| **Blazing Fire** | 🔥 | `5104841245755180586` |
| **Thumbs Up** | 👍 | `5107584321108051014` |
| **Heart / Love** | ❤️ | `5159385139981059251` |
| **Poop / Joke** | 💩 | `5046134037148567282` |

```php
function send_effect_message(
    string|int $chatId,
    string $text,
    string $effectId = '5046509860389126442',
    array $extra = []
): array {
    return bot('sendMessage', array_merge([
        'chat_id'           => $chatId,
        'text'              => $text,
        'parse_mode'        => 'HTML',
        'message_effect_id' => $effectId
    ], $extra));
}

// Example: Celebrate user cashout or reward
send_effect_message(
    $chatId,
    "🎉 <b>CONGRATULATIONS!</b>\nYour withdrawal of $50.00 has been approved!",
    '5046509860389126442' // Confetti
);
```

---

### 4.38. ⭐ Telegram Star Subscriptions & Recurring Billing (`createInvoiceLink`, `editUserStarSubscription`)

Telegram Bot API 8.0 & 8.1 introduced native **recurring monthly/annual subscriptions** paid in Telegram Stars (`currency: XTR`).

#### 1. Generating a Recurring Subscription Invoice Link
Specify the `subscription_period` parameter (in seconds). For example, 30 days = `2592000` seconds:

```php
function create_star_subscription_link(
    string $title,
    string $description,
    int $starsPerPeriod,
    string $payload,
    int $periodSeconds = 2592000
): ?string {
    $res = bot('createInvoiceLink', [
        'title'               => $title,
        'description'         => $description,
        'payload'             => $payload,
        'currency'            => 'XTR',
        'prices'              => [['label' => $title, 'amount' => $starsPerPeriod]],
        'subscription_period' => $periodSeconds // 30-day recurring subscription
    ]);
    return $res['result'] ?? null;
}
```

#### 2. Processing Subscription Renewals in Webhook
In Bot API 8.1+, `successful_payment` contains recurring flags:

```php
if (isset($message['successful_payment'])) {
    $sp = $message['successful_payment'];
    $isRecurring = !empty($sp['is_recurring']);
    $expiresAt   = $sp['subscription_expiration_date'] ?? 0;
    $telegramPaymentChargeId = $sp['telegram_payment_charge_id'] ?? '';

    // Record subscription in SQLite database
    $st = $db->prepare("INSERT INTO subscriptions (user_id, status, expires_at, charge_id)
        VALUES (?, 'active', ?, ?)
        ON CONFLICT(user_id) DO UPDATE SET expires_at=excluded.expires_at, status='active'");
    $st->execute([$chatId, $expiresAt, $telegramPaymentChargeId]);

    bot('sendMessage', [
        'chat_id' => $chatId,
        'text'    => "⭐ <b>Subscription Active!</b>\nValid until: <b>" . date('Y-m-d H:i', $expiresAt) . "</b>",
        'parse_mode' => 'HTML'
    ]);
}
```

#### 3. Canceling or Editing a Subscription (`editUserStarSubscription`)
Allow users or admins to cancel auto-renewal:
```php
function cancel_star_subscription(int $userId, string $telegramPaymentChargeId): array {
    return bot('editUserStarSubscription', [
        'user_id'                    => $userId,
        'telegram_payment_charge_id' => $telegramPaymentChargeId,
        'is_canceled'                => true
    ]);
}
```

---

### 4.39. 🎁 Sending Telegram Gifts to Users & Channels (`sendGift`, `getAvailableGifts`)

Telegram Bot API 8.2 & 8.3 allows bots to purchase and send collectible Gifts using Telegram Stars:

#### 1. Retrieve Current Gifts Catalog
```php
function get_telegram_gifts(): array {
    $res = bot('getAvailableGifts');
    return $res['result']['gifts'] ?? [];
}
```

#### 2. Send Gift to a User or Channel
```php
// Send Gift to a User:
function send_gift_to_user(int $userId, string $giftId, string $congratsText = ''): array {
    $params = [
        'user_id' => $userId,
        'gift_id' => $giftId
    ];
    if ($congratsText !== '') {
        $params['text'] = $congratsText;
        $params['text_parse_mode'] = 'HTML';
    }
    return bot('sendGift', $params);
}

// Send Gift to a Channel (Bot API 8.3):
function send_gift_to_channel(string|int $channelChatId, string $giftId): array {
    return bot('sendGift', [
        'chat_id' => $channelChatId,
        'gift_id' => $giftId
    ]);
}
```

---

### 4.40. 🔗 Modern Link Previews Control (`link_preview_options`)

Replace deprecated `disable_web_page_preview` with full granular control over preview layouts:

```php
// 1. Disable preview entirely:
bot('sendMessage', [
    'chat_id'              => $chatId,
    'text'                 => 'Visit https://example.com for info.',
    'link_preview_options' => ['is_disabled' => true]
]);

// 2. Select specific URL and force large hero banner preview:
bot('sendMessage', [
    'chat_id'              => $chatId,
    'text'                 => 'Check our guides: https://botlify.cloud and https://t.me/channel',
    'link_preview_options' => [
        'url'                => 'https://botlify.cloud',
        'prefer_large_media' => true,
        'show_above_text'    => false
    ]
]);

// 3. Compact mini-preview shown ABOVE text:
bot('sendMessage', [
    'chat_id'              => $chatId,
    'text'                 => 'Read the latest blog post at https://example.com/article',
    'link_preview_options' => [
        'prefer_small_media' => true,
        'show_above_text'    => true
    ]
]);
```

---

### 4.41. 🎬 Enhanced Video Controls (`sendVideo` with `cover` & `start_timestamp`)

Telegram Bot API 8.3 allows bots to set custom video cover images and playback starting offsets:

```php
bot('sendVideo', [
    'chat_id'         => $chatId,
    'video'           => 'https://example.com/tutorial.mp4',
    'caption'         => '🎬 <b>Watch Chapter 2: Database Setup</b>',
    'parse_mode'      => 'HTML',
    'cover'           => 'https://example.com/chapter2_thumbnail.jpg', // Custom video cover
    'start_timestamp' => 45, // Skip intro and start playback at 00:45
    'supports_streaming' => true
]);
```

---

### 4.42. 📨 Batch Message Operations (`copyMessages`, `forwardMessages`)

Efficiently forward or clone up to 100 messages at once without looping single API calls:

```php
// Batch copy messages from storage channel to user chat:
function batch_copy_messages(
    string|int $toChatId,
    string|int $fromChatId,
    array $messageIds
): array {
    return bot('copyMessages', [
        'chat_id'      => $toChatId,
        'from_chat_id' => $fromChatId,
        'message_ids'  => array_values($messageIds) // e.g. [101, 102, 103]
    ]);
}

// Batch forward without modifying attribution:
function batch_forward_messages(
    string|int $toChatId,
    string|int $fromChatId,
    array $messageIds
): array {
    return bot('forwardMessages', [
        'chat_id'      => $toChatId,
        'from_chat_id' => $fromChatId,
        'message_ids'  => array_values($messageIds)
    ]);
}
```

---

### 4.43. 🛡️ Verification Badges & Organization Checks (`verifyUser`, `verifyChat`)

Telegram Bot API 8.2 allows certified bots to assign or revoke verification badges on behalf of companies, corporate registries, or educational institutions:

```php
// Verify a student or verified client
function verify_community_user(int $userId, string $description = 'Verified VIP Trader'): array {
    return bot('verifyUser', [
        'user_id'            => $userId,
        'custom_description' => $description
    ]);
}

// Remove verification if subscription expires
function revoke_community_user_verification(int $userId): array {
    return bot('removeUserVerification', [
        'user_id' => $userId
    ]);
}
```

---

### 4.44. 🕹️ Telegram HTML5 Games Engine (`sendGame`, `setGameScore`, `getGameHighScores`)

Telegram bots can host and launch interactive HTML5 canvas games directly within the Telegram app, complete with real-time multiplayer leaderboards and high score tracking!

#### 1. Sending a Game Card (`sendGame`):
```php
function send_bot_game(string|int $chatId, string $gameShortName): array {
    return bot('sendGame', [
        'chat_id'         => $chatId,
        'game_short_name' => $gameShortName, // Configured via BotFather /newgame
        'reply_markup'    => [
            'inline_keyboard' => [
                [
                    ['text' => '🎮 Play Now!', 'callback_game' => []]
                ],
                [
                    ['text' => '🏆 Leaderboard', 'callback_data' => 'game_leaderboard']
                ]
            ]
        ]
    ]);
}
```

#### 2. Launching the Game on Button Click:
When the user taps the "Play Now" button, Telegram sends a callback query with `game_short_name`. Respond with `answerCallbackQuery` pointing to your game URL:
```php
if ($cb && isset($cb['game_short_name'])) {
    $gameUrl = 'https://botlify.cloud/games/flappy_star/?user=' . $cb['from']['id'];
    bot('answerCallbackQuery', [
        'callback_query_id' => $cb['id'],
        'url'               => $gameUrl
    ]);
    exit;
}
```

#### 3. Submitting Scores & Leaderboard (`setGameScore`, `getGameHighScores`):
```php
// Save user score (from your game backend):
function record_user_score(int $userId, int $score, int $chatId, int $messageId): array {
    return bot('setGameScore', [
        'user_id'    => $userId,
        'score'      => $score,
        'chat_id'    => $chatId,
        'message_id' => $messageId,
        'force'      => true
    ]);
}

// Fetch Top Scores:
function get_game_leaderboard(int $userId, int $chatId, int $messageId): array {
    $res = bot('getGameHighScores', [
        'user_id'    => $userId,
        'chat_id'    => $chatId,
        'message_id' => $messageId
    ]);
    return $res['result'] ?? [];
}
```

---

### 4.45. ⏳ Chat Action Typing Indicators (`sendChatAction`)

Sending chat actions before processing AI responses, database searches, or media generation keeps users informed and dramatically reduces perceived waiting time:

| Action Parameter | Telegram UI Status Display |
| :--- | :--- |
| `'typing'` | *"typing..."* (Best for AI, text generation) |
| `'upload_photo'` | *"sending photo..."* |
| `'record_video'` / `'upload_video'` | *"sending video..."* |
| `'record_voice'` / `'upload_voice'` | *"sending voice message..."* |
| `'upload_document'` | *"sending file..."* |
| `'choose_sticker'` | *"choosing a sticker..."* |
| `'find_location'` | *"finding location..."* |

```php
function send_typing(string|int $chatId, string $action = 'typing'): array {
    return bot('sendChatAction', [
        'chat_id' => $chatId,
        'action'  => $action
    ]);
}

// Practical usage before heavy AI completion:
send_typing($chatId, 'typing');
$aiReply = query_gemini_or_openai($userPrompt);
bot('sendMessage', ['chat_id' => $chatId, 'text' => $aiReply, 'parse_mode' => 'HTML']);
```

---

### 4.46. 🔐 Seamless Telegram Web OAuth Login (`login_url`)

Authenticate Telegram users on your web application or Mini App with 1 tap using `login_url` inline buttons. No passwords, SMS, or OTPs required!

```php
function send_web_login_button(string|int $chatId): array {
    return bot('sendMessage', [
        'chat_id'      => $chatId,
        'text'         => '🔐 <b>Access Your Web Dashboard:</b>\nClick below to securely authenticate your account.',
        'parse_mode'   => 'HTML',
        'reply_markup' => [
            'inline_keyboard' => [
                [
                    [
                        'text'      => '🚀 Log in to Web Studio',
                        'login_url' => [
                            'url'                  => 'https://botlify.cloud/auth/telegram_callback.php',
                            'forward_text'         => 'Log in to Botlify Cloud',
                            'bot_username'         => BOT_USERNAME,
                            'request_write_access' => true
                        ]
                    ]
                ]
            ]
        ]
    ]);
}
```

#### Verifying the Telegram Auth Hash in PHP:
```php
function verify_telegram_auth(array $authData, string $botToken): bool {
    $checkHash = $authData['hash'] ?? '';
    unset($authData['hash']);
    $dataCheckArr = [];
    foreach ($authData as $key => $value) {
        $dataCheckArr[] = $key . '=' . $value;
    }
    sort($dataCheckArr);
    $dataCheckString = implode("\n", $dataCheckArr);
    $secretKey = hash('sha256', $botToken, true);
    $hash = hash_hmac('sha256', $dataCheckString, $secretKey);
    return hash_equals($hash, $checkHash) && (time() - (int)$authData['auth_date'] < 86400);
}
```

---

### 4.47. 🔘 Interactive Keyboard Request Selectors (`request_users`, `request_chat`, `request_contact`, `request_location`, `request_poll`)

Allow users to select other users, channels, phone numbers, GPS coordinates, or polls using Telegram's native picker dialogs:

```php
$selectorKeyboard = [
    'keyboard' => [
        // 1. Pick Users or Bots
        [
            [
                'text'          => '👥 Pick a Friend to Invite',
                'request_users' => [
                    'request_id'   => 1,
                    'is_bot'       => false,
                    'max_quantity' => 1
                ]
            ]
        ],
        // 2. Pick Channel or Group where Bot is Admin
        [
            [
                'text'         => '📢 Select Your Channel',
                'request_chat' => [
                    'request_id'     => 2,
                    'chat_is_channel' => true,
                    'bot_is_member'  => true
                ]
            ]
        ],
        // 3. Share Verified Phone Number & Location
        [
            ['text' => '📱 Share Phone',    'request_contact'  => true],
            ['text' => '📍 Share Location', 'request_location' => true]
        ],
        // 4. Create Quiz Poll
        [
            ['text' => '📊 Create Quiz',    'request_poll'     => ['type' => 'quiz']]
        ]
    ],
    'resize_keyboard' => true,
    'one_time_keyboard' => true
];

bot('sendMessage', [
    'chat_id'      => $chatId,
    'text'         => '👇 <b>Please select an action from the menu:</b>',
    'parse_mode'   => 'HTML',
    'reply_markup' => $selectorKeyboard
]);
```

---

### 4.48. 🔗 Dynamic Chat Invite Links with Limits & Expiry (`createChatInviteLink`, `revokeChatInviteLink`)

Create single-use, timed, or paid invite links for VIP communities and subscription tiers:

```php
function create_timed_vip_invite(string|int $channelId, int $hoursValid = 24, int $maxUses = 1): ?string {
    $res = bot('createChatInviteLink', [
        'chat_id'              => $channelId,
        'name'                 => 'VIP Pass (24h Single-Use)',
        'expire_date'          => time() + ($hoursValid * 3600),
        'member_limit'         => $maxUses,
        'creates_join_request' => false
    ]);
    return $res['result']['invite_link'] ?? null;
}

// Revoke an old invite link:
function revoke_vip_invite(string|int $channelId, string $inviteLink): array {
    return bot('revokeChatInviteLink', [
        'chat_id'     => $channelId,
        'invite_link' => $inviteLink
    ]);
}
```

---

### 4.49. 🖼️ User Profile Photos & File Downloads (`getUserProfilePhotos`, `getFile`)

Inspect user profile avatars and download media files directly from Telegram servers:

```php
// 1. Get user profile photos
function get_user_avatar_file_id(int $userId): ?string {
    $res = bot('getUserProfilePhotos', ['user_id' => $userId, 'limit' => 1]);
    $photos = $res['result']['photos'] ?? [];
    if (!empty($photos[0])) {
        // Last element in size array is highest resolution
        $largest = end($photos[0]);
        return $largest['file_id'] ?? null;
    }
    return null;
}

// 2. Resolve direct download URL on Telegram CDN
function get_telegram_file_download_url(string $fileId): ?string {
    $res = bot('getFile', ['file_id' => $fileId]);
    $filePath = $res['result']['file_path'] ?? null;
    if ($filePath) {
        return 'https://api.telegram.org/file/bot' . BOT_TOKEN . '/' . $filePath;
    }
    return null;
}
```

---

### 4.50. 📚 The Complete A-to-Z Telegram Bot API Master Reference Matrix

Quick alphabetical reference for all **100+ official Telegram Bot API methods**:

| Method Name | Category | Primary Purpose & Usage |
| :--- | :--- | :--- |
| `answerCallbackQuery` | UI / Callbacks | Dismiss button spinners & show popup alert modals |
| `answerInlineQuery` | Inline Mode | Deliver instant search query results directly in chat |
| `answerPreCheckoutQuery` | Payments / Stars | Approve or reject payment before funds are charged |
| `answerShippingQuery` | Payments | Provide shipping prices and delivery options |
| `answerWebAppQuery` | Mini Apps | Send inline message from Mini App to chat |
| `approveChatJoinRequest` | Administration | Accept pending join request to private group/channel |
| `banChatMember` | Moderation | Kick and ban user from group/channel |
| `banChatSenderChat` | Moderation | Ban channel from sending messages in group |
| `close` | Instance Control | Close bot instance before moving to local server |
| `copyMessage` | Messaging | Copy message to chat with optional new caption |
| `copyMessages` | Batch Messaging | Batch copy up to 100 messages at once |
| `createChatInviteLink` | Administration | Generate timed or member-limited invite link |
| `createChatSubscriptionInviteLink` | Stars / Subscriptions | Generate recurring Stars subscription invite link |
| `createForumTopic` | Forum Groups | Create forum topic with name and icon |
| `createInvoiceLink` | Payments / Stars | Generate shareable payment or subscription link |
| `createNewStickerSet` | Stickers | Programmatically create a new sticker pack |
| `declineChatJoinRequest` | Administration | Reject pending join request |
| `deleteChatPhoto` | Administration | Remove chat profile photo |
| `deleteChatStickerSet` | Administration | Remove group sticker set |
| `deleteMessage` | Moderation | Delete single message |
| `deleteMessages` | Moderation | Batch delete up to 100 messages at once |
| `deleteMyCommands` | Customization | Clear registered slash commands |
| `deleteStickerFromSet` | Stickers | Remove sticker from pack |
| `deleteWebhook` | Updates | Remove webhook and switch to long polling |
| `editChatInviteLink` | Administration | Edit existing invite link parameters |
| `editForumTopic` | Forum Groups | Rename topic or change icon |
| `editGeneralForumTopic` | Forum Groups | Edit general topic in forum |
| `editMessageCaption` | Messaging | Edit caption of existing media message |
| `editMessageLiveLocation` | Location | Update live GPS coordinates of moving message |
| `editMessageMedia` | Media | Replace photo/video inside existing message |
| `editMessageReplyMarkup` | UI / Keyboards | Update or remove inline button keyboards |
| `editMessageText` | Messaging | Update text and buttons of existing message |
| `editUserStarSubscription` | Stars / Subscriptions | Cancel or extend user's Star recurring subscription |
| `exportChatInviteLink` | Administration | Generate primary public invite link |
| `forwardMessage` | Messaging | Forward message with original author credit |
| `forwardMessages` | Batch Messaging | Batch forward up to 100 messages at once |
| `getAvailableGifts` | Gifts | Fetch available Telegram collectible gifts catalog |
| `getBusinessConnection` | Business | Fetch business account connection status |
| `getChat` | Administration | Get full chat metadata, description, and permissions |
| `getChatAdministrators` | Administration | Fetch list of chat admins and creators |
| `getChatMember` | Moderation | Fetch specific user membership status in channel |
| `getChatMemberCount` | Administration | Get total member count of chat/channel |
| `getChatMenuButton` | Customization | Fetch current bottom-left menu button config |
| `getFile` | Files / Media | Get file path on Telegram CDN for downloading |
| `getGameHighScores` | Games | Fetch top leaderboard scores for game |
| `getMe` | Information | Verify bot token and fetch bot identity |
| `getMyCommands` | Customization | View registered slash commands |
| `getMyDefaultAdministratorRights` | Administration | Get default bot permissions for groups |
| `getMyDescription` | Onboarding | Get bot bio description |
| `getMyName` | Onboarding | Get bot display name |
| `getMyShortDescription` | Onboarding | Get short about text |
| `getStickerSet` | Stickers | Get stickers and metadata of pack |
| `getUpdates` | Updates | Long-polling update fetcher |
| `getUserChatBoosts` | Channel Boosts | Fetch boosts applied to chat by a user |
| `getUserProfilePhotos` | User Metadata | Fetch user profile avatar photos |
| `getWebhookInfo` | Updates | Check current webhook status and error flags |
| `hideGeneralForumTopic` | Forum Groups | Hide General topic in forum supergroup |
| `leaveChat` | Administration | Bot exits group or channel |
| `logOut` | Instance Control | Log out from cloud Bot API before local migration |
| `pinChatMessage` | Administration | Pin message to top of chat |
| `promoteChatMember` | Administration | Promote user to administrator with permissions |
| `refundStarPayment` | Payments / Stars | Refund Telegram Stars transaction to user |
| `reopenForumTopic` | Forum Groups | Reopen closed forum topic |
| `reopenGeneralForumTopic` | Forum Groups | Reopen closed General topic |
| `replaceStickerInSet` | Stickers | Replace a sticker inside pack |
| `restrictChatMember` | Moderation | Restrict user permissions (mute, media ban) |
| `revokeChatInviteLink` | Administration | Deactivate chat invite link |
| `savePreparedInlineMessage` | Mini Apps | Pre-generate inline message for Mini App sharing |
| `sendAnimation` | Media | Send animated GIF or silent MP4 loop |
| `sendAudio` | Media | Send MP3 music with artist & title tags |
| `sendChatAction` | Indicators | Send typing / uploading photo status |
| `sendContact` | Contacts | Send phone contact card |
| `sendDice` | Entertainment | Roll animated dice, dart, football, or slots |
| `sendDocument` | Files | Send PDF, ZIP, code, or any document file |
| `sendGame` | Games | Send HTML5 game card |
| `sendGift` | Gifts | Send Telegram Stars gift to user or channel |
| `sendInvoice` | Payments / Stars | Send payment invoice for goods or Stars |
| `sendLocation` | Location | Send GPS coordinates map point |
| `sendMediaGroup` | Media | Send album of up to 10 photos/videos |
| `sendMessage` | Messaging | Primary text messaging method |
| `sendPaidMedia` | Stars / Paid Media | Send Star-gated paywalled photos or videos |
| `sendPhoto` | Media | Send JPG/PNG image with caption |
| `sendPoll` | Polls | Send regular poll or trivia quiz |
| `sendSticker` | Stickers | Send static, animated (TGS), or video sticker |
| `sendVenue` | Location | Send venue with title, address, and Foursquare ID |
| `sendVideo` | Media | Send MP4 video with cover and start timestamp |
| `sendVideoNote` | Media | Send circular video note bubble |
| `sendVoice` | Media | Send OGG voice memo |
| `setChatAdministratorCustomTitle` | Administration | Set custom title badge for admin (e.g. "Founder") |
| `setChatDescription` | Administration | Set group or channel description |
| `setChatMenuButton` | Customization | Set bottom-left button (Commands, WebApp, Default) |
| `setChatPermissions` | Moderation | Set default permissions for all group members |
| `setChatPhoto` | Administration | Upload new chat profile picture |
| `setChatTitle` | Administration | Rename group or channel |
| `setGameScore` | Games | Record high score for user in game |
| `setMessageReaction` | Reactions | Add emoji reaction (👍, 🔥, 🎉) to message |
| `setMyCommands` | Customization | Register slash command menu with scopes |
| `setMyDefaultAdministratorRights` | Administration | Set default rights for when bot is added to chats |
| `setMyDescription` | Onboarding | Set what bot does (empty chat screen) |
| `setMyName` | Onboarding | Change bot display name |
| `setMyShortDescription` | Onboarding | Set bot about info |
| `setPassportDataErrors` | Passport | Report verification errors in Telegram Passport |
| `setUserEmojiStatus` | User Status | Set custom emoji status for premium user |
| `setWebhook` | Updates | Point Telegram webhook to Botlify gateway |
| `stopMessageLiveLocation` | Location | End live location sharing |
| `stopPoll` | Polls | Close active poll and reveal final results |
| `unbanChatMember` | Moderation | Remove ban from user |
| `unbanChatSenderChat` | Moderation | Allow channel to send messages in group again |
| `unhideGeneralForumTopic` | Forum Groups | Unhide General forum topic |
| `unpinAllChatMessages` | Administration | Clear all pinned messages in chat |
| `unpinAllForumTopicMessages` | Forum Groups | Clear pins in specific topic |
| `unpinChatMessage` | Administration | Unpin specific message |
| `uploadStickerFile` | Stickers | Upload sticker file for new pack creation |
| `verifyChat` | Verification | Assign verified badge to chat for organization |
| `verifyUser` | Verification | Assign verified badge to user for organization |

---

---

## 5. 🛠️ Botlify Model Context Protocol (MCP) Server & 37 Tools Specification

Connect your AI coding assistants—including **Claude Desktop**, **Cursor IDE**, **Antigravity**, **Windsurf**, and custom LLM agents—directly to your Free Bot Host account using the **Model Context Protocol (MCP)**.

With this MCP integration, your AI assistant can directly inspect your Telegram bots, write & edit PHP code, run syntax checks, manage scheduled cron jobs, query SQLite databases, and monitor broadcast statistics using natural language!

---

### 💡 What is MCP?

**Model Context Protocol (MCP)** is an open protocol standard developed by Anthropic that allows AI models to safely access external tools, databases, and filesystem contexts in real-time.

By linking Free Bot Host to your AI assistant:
- The AI can read your `index.php` or any handler file, write code updates, and verify syntax automatically.
- The AI can inspect your bot's SQLite database schema (`storage/database.db`) and write queries to debug issues.
- The AI can view active cron jobs, test them, and report execution errors.

---

### 🌐 Server Endpoint & Authentication

#### Endpoint URL:
```http
https://your-domain.com/mcp.php?key=fbh_usr_your_api_key_here
```

#### Where to get your API Key:
1. Open the **Mini App** dashboard.
2. Go to the **Profile** tab.
3. Locate the **Developer API & MCP Protocol** section.
4. Copy your API Key or click **🔄 Regenerate Key** if you ever need to reset it.

---

### 🔌 Connecting with AI Clients

#### 1. Claude Desktop Configuration

Claude Desktop supports MCP servers via its configuration file `claude_desktop_config.json`:

- **Windows**: `%APPDATA%\Claude\claude_desktop_config.json`
- **macOS**: `~/Library/Application Support/Claude/claude_desktop_config.json`

Add the following block to your `mcpServers` configuration:

```json
{
  "mcpServers": {
    "free-bot-host": {
      "command": "npx",
      "args": [
        "-y",
        "mcp-remote-client",
        "https://your-domain.com/mcp.php?key=fbh_usr_your_api_key_here"
      ]
    }
  }
}
```

> 💡 *Note*: If your client supports direct HTTP/SSE MCP endpoints, you can directly specify `https://your-domain.com/mcp.php?key=fbh_usr_your_api_key_here`.

---

#### 2. Cursor IDE Configuration

Cursor IDE supports MCP servers natively in settings:

1. Open **Cursor Settings** (`Ctrl + Shift + J` or `Cmd + Shift + J`).
2. Navigate to **Features** -> **MCP**.
3. Click **+ Add New MCP Server**.
4. Configure the server:
   - **Name**: `FreeBotHost`
   - **Type**: `command` or `remote`
   - **Command / URL**:
     ```bash
     npx -y mcp-remote-client "https://your-domain.com/mcp.php?key=fbh_usr_your_api_key_here"
     ```
5. Click **Save** and verify that tools appear with green checkmarks.

---

#### 3. Antigravity / Generic MCP Client

For custom MCP client runners or Node-based bridges:

```bash
npx -y @modelcontextprotocol/inspector https://your-domain.com/mcp.php?key=fbh_usr_your_api_key_here
```

---

### 🛠️ Available MCP Tools Reference

Your AI assistant has access to **29 specialized tools**:

#### 🛠️ Bot Building, Scaffolding & Webhook Testing (NEW)
| Tool Name | Description | Key Arguments |
|---|---|---|
| `get_bot_making_guide` | Retrieves master bot development docs, best practices & styled keyboard guide | `section` (optional: `keyboards`, `database`, `cron`, etc.) |
| `scaffold_bot_code` | Generates complete, production-ready bot boilerplate with styled buttons | `type` (`styled_keyboard`, `database_bot`, `shop_bot`), `bot_name` |
| `install_bot_scaffold` | Deploys a production scaffold directly to bot's `index.php` | `bot_id`, `type` |
| `validate_bot_code` | Performs deep syntax verification & lint checks before saving/running | `code` |
| `test_bot_webhook` | Simulates live Telegram Webhook POST updates in sandbox and captures logs | `bot_id`, `update` (optional) |

#### 📚 Botlify Knowledge Base & Documentation Engine (NEW)
| Tool Name | Description | Key Arguments |
|---|---|---|
| `about_botlify` | Comprehensive A-to-Z overview of Botlify Cloud: architecture, serverless PHP 8.2+ runtime, SQLite WAL database, 20ms cURL engine, security sandboxing, webhook lifecycle, key features, and developer rules | None |
| `get_full_docs` | Retrieves complete, unabridged master developer documentation for Botlify Cloud from `docs/docs.md` (14 chapters, full Telegram Bot API 203 methods & 401 types, MCP server, REST API, Broadcast network, Blog engine, and GitHub backup) | `offset` (optional), `limit` (optional) |
| `list_docs` | Lists all 638 documentation topics, platform guides, Telegram Bot API methods, and types with their categories, summaries, read times, and canonical URLs | None |
| `search_docs` | Searches documentation and Telegram Bot API reference by keyword or phrase. Returns scored matching articles with relevance snippets and canonical URLs | `query` (required), `max_results` (optional, default 10) |

#### 🎨 Styled Keyboard Colors Reference
Telegram Mini Apps and modern Telegram bot clients support button style attributes:

| Style | Color | Primary Usage |
| :--- | :--- | :--- |
| `primary` | **Blue** 🔵 | Main Actions, Launch App, Next, Open Menu, Confirm |
| `success` | **Green** 🟢 | Buy Now, Deposit, Pay, Approve, Activate |
| `danger`  | **Red** 🔴 | Delete, Cancel, Reset, Reject, Stop |

```php
// Inline Keyboard with Styles:
$inlineKeyboard = [
    'inline_keyboard' => [
        [
            ['text' => '🚀 Launch App', 'callback_data' => 'launch', 'style' => 'primary'], // Blue
            ['text' => '💳 Buy VIP', 'callback_data' => 'buy', 'style' => 'success']       // Green
        ],
        [
            ['text' => '❌ Cancel', 'callback_data' => 'cancel', 'style' => 'danger']       // Red
        ]
    ]
];
$reply_markup = json_encode($inlineKeyboard);

// Reply Keyboard with Styles:
$replyKeyboard = [
    'keyboard' => [
        [
            ['text' => '🟢 Activate Service', 'style' => 'success'],
            ['text' => '🔵 Account Dashboard', 'style' => 'primary']
        ],
        [
            ['text' => '🔴 Terminate Session', 'style' => 'danger']
        ]
    ],
    'resize_keyboard' => true
];
$reply_markup = json_encode($replyKeyboard);
```

#### 🤖 Bot Management
| Tool Name | Description | Key Arguments |
|---|---|---|
| `list_bots` | Lists bots owned by you. Default returns only active bots (excludes recycle bin). | `status` (`active` [default], `deleted`, `all`) |
| `get_bot_info` | Retrieves comprehensive info for a bot by ID or username | `bot_id` |
| `create_bot` | Deploys a new bot using a Telegram BotFather token | `token`, `admin_chat_id` |
| `delete_bot` | Moves bot to recycle bin (soft delete), or permanently deletes when `permanent: true` | `bot_id`, `permanent` (optional boolean, default `false`) |
| `restore_bot` | Restores a deleted bot from the recycle bin back to active status & resets webhook | `bot_id` |
| `restart_bot` | Refreshes webhook, tests connection, and resets error flags | `bot_id` |

#### 📁 Filesystem & Code Editing
| Tool Name | Description | Key Arguments |
|---|---|---|
| `list_files` | Lists files and sub-folders in bot directory | `bot_id`, `path` |
| `read_file` | Reads source code or contents of any bot file | `bot_id`, `file` |
| `write_file` | Writes/edits code with automated PHP syntax verification | `bot_id`, `file`, `content` |
| `create_file` | Creates a new file in a bot directory | `bot_id`, `name`, `path`, `content` |
| `create_folder` | Creates a new subdirectory in bot workspace | `bot_id`, `name`, `path` |
| `delete_file` | Deletes a file or directory | `bot_id`, `file` |

#### ⚙️ Environment Variables (.env)
| Tool Name | Description | Key Arguments |
|---|---|---|
| `get_env_variables` | Returns parsed environment key-value pairs | `bot_id` |
| `set_env_variables` | Updates environment variables in `.env` | `bot_id`, `variables` |

#### ⏰ Cron Tasks Automation
| Tool Name | Description | Key Arguments |
|---|---|---|
| `list_cron_jobs` | Lists all scheduled background cron tasks | `bot_id` |
| `create_cron_job` | Schedules a new cron script | `bot_id`, `script_path`, `interval_type` |
| `run_cron_job` | Runs a cron task immediately and inspects logs | `bot_id`, `cron_id` |

#### 🗄️ Database Operations (SQLite)
| Tool Name | Description | Key Arguments |
|---|---|---|
| `get_database_schema` | Returns database tables, column types, and row count | `bot_id` |
| `query_database` | Runs sandboxed SQL queries on `storage/database.db` | `bot_id`, `query` |

#### 📢 Broadcast Studio
| Tool Name | Description | Key Arguments |
|---|---|---|
| `get_broadcast_stats` | Inspects subscriber count and 7-day activity | `bot_id` |
| `send_broadcast` | Launches a broadcast to bot audience | `bot_id`, `message`, `audience` |

#### 👤 Account & Marketplace
| Tool Name | Description | Key Arguments |
|---|---|---|
| `get_profile` | Retrieves user account limits, bot slots, referral count | none |
| `get_wallet` | Retrieves balance, sales earnings, and transactions | none |
| `browse_store` | Browses templates and bots in the marketplace | `search`, `category` |
| `install_store_bot` | Installs a bot template directly into user account | `store_id`, `token` |

#### 📦 Bot Code Transfer System
| Tool Name | Description | Key Arguments |
|---|---|---|
| `create_bot_transfer` | Generates a 72-hour transfer code for sending bot code to another user | `bot_id`, `target_recipient` |
| `list_bot_transfers` | Lists pending incoming and outgoing bot code transfers | none |
| `get_transfer_info` | Checks the status, bot name, and expiration of a transfer code | `transfer_code` |
| `accept_bot_transfer` | Accepts an incoming bot transfer and deploys it with your Bot Token | `transfer_code`, `token`, `admin_chat_id` |
| `reject_bot_transfer` | Rejects and cancels an incoming bot transfer offer | `transfer_id` |

---

### 📚 Available MCP Resources

The MCP server exposes live bot resources using the `fbh://` URI scheme:

- `fbh://docs/botmaking` — Complete Telegram Bot Making & Styled Keyboard Guide (`botmakingdocs.md`).
- `fbh://bots/{bot_id}/info` — Real-time bot metadata and runtime status.
- `fbh://bots/{bot_id}/schema` — SQLite database schema and tables.
- `fbh://bots/{bot_id}/env` — Active `.env` file variables.

Your AI model can attach these resources directly into its conversation context for zero-latency awareness.

---

### 🎯 Available MCP Prompts

1. **`create_styled_keyboard_bot`**:
   - Scaffolds and deploys a modern Telegram bot with primary (Blue), success (Green), and danger (Red) styled inline/reply buttons.
2. **`bot_health_check`**:
   - Diagnoses webhook health, syntax errors, cron task status, and database integrity for any bot.
3. **`code_audit_and_enhance`**:
   - Reads your bot's code, identifies potential security risks or logic bugs, and suggests modern enhancements.

---

### 💬 Example AI Prompts & Use Cases

Once connected, you can ask your AI assistant questions like:

#### 1. Code Development
> *"List all files in my bot @MyShopBot. Read `index.php` and add a new `/help` command that lists all available products."*

#### 2. Database Inspection & Debugging
> *"Inspect the database schema of bot ID 2. How many users are registered? Show me the 5 most recently active users."*

#### 3. Background Task Scheduling
> *"Create a new cron job for bot ID 3 that runs `tasks/cleanup.php` once every day."*

#### 4. Audience Broadcasting
> *"Check the subscriber count of bot ID 1. If there are more than 10 users, send a broadcast announcing our weekend discount."*

---

### ❓ Troubleshooting & FAQ

##### 1. Why do I get "Unauthorized" error?
- Ensure you have generated an API Key from the Mini App Profile tab.
- Ensure the key parameter is passed properly in the query string (`?key=fbh_usr_...`) or `X-API-KEY` header.

##### 2. Can the AI delete my entire account?
- No. The API is strictly scoped to the authenticated user's bots. Destructive operations like `delete_bot` only perform a soft-delete (moving to the 7-day recycle bin), which can easily be restored.
- The SQLite query tool is strictly isolated to the bot's own `storage/database.db`. Host-level file tampering or database cross-talk is prevented.

##### 3. What if I regenerate my API key?
- Once you click **🔄 Regenerate Key** in the Mini App, your old key is immediately revoked. You must update your `claude_desktop_config.json` or Cursor MCP settings with the new key.

---

## 6. 🌐 Developer REST API (user_api.php) Reference

Welcome to the official Developer REST API of **Free Bot Host**. This API empowers you to manage all aspects of your hosted Telegram bots remotely, automate deployments, integrate with CI/CD pipelines, or control your bots programmatically using any programming language.

---

### 🌐 Overview & Base URL

The API endpoint is hosted on your Free Bot Host installation:

```http
https://your-domain.com/user_api.php
```

All requests can be sent via `GET` or `POST` (supporting JSON `application/json` as well as `multipart/form-data` and `application/x-www-form-urlencoded`).

---

### 🔑 Authentication

Every request to `user_api.php` requires your personal **API Key**. You can pass your key using any of the following 3 standard methods:

#### Method 1: Custom HTTP Header (Recommended)
```http
X-API-KEY: fbh_usr_0123456789abcdef0123456789abcdef01234567
```

#### Method 2: Authorization Bearer Header
```http
Authorization: Bearer fbh_usr_0123456789abcdef0123456789abcdef01234567
```

#### Method 3: Query Parameter or POST Field
```http
https://your-domain.com/user_api.php?api_key=fbh_usr_0123456789abcdef0123456789abcdef01234567&action=list_bots
```

---

### ⚙️ Managing Your API Key

1. Open the Telegram Mini App dashboard.
2. Click on the **Profile** tab in the navigation bar.
3. Locate the **Developer API & MCP Protocol** card.
4. Your personal API Key is automatically generated (`fbh_usr_...`).
5. Click **📋 Copy** to copy it to your clipboard.
6. Click **🔄 Regenerate Key** at any time to invalidate old credentials and generate a fresh key.

---

### 📦 Request & Response Formats

All successful API responses return a JSON object with `"ok": true`. In case of errors, the response contains `"ok": false` along with an informative `"error"` message.

#### Standard Success Response:
```json
{
  "ok": true,
  "...": "..."
}
```

#### Standard Error Response:
```json
{
  "ok": false,
  "error": "Bot not found or access denied."
}
```

---

### 📑 Endpoints Reference

#### 1. User & Profile

##### Get User Profile & Quotas
- **Action**: `profile` or `get_profile`
- **Method**: `GET` / `POST`
- **Example**:
  ```http
  GET /user_api.php?action=get_profile
  ```
- **Response**:
  ```json
  {
    "ok": true,
    "user": {
      "id": 1,
      "chat_id": "123456789",
      "first_name": "John",
      "username": "john_dev",
      "balance": 15.50,
      "balance_formatted": "15.50 USDT",
      "bot_limit": 5,
      "used_bots": 2,
      "available_slots": 3,
      "storage_mb": 50,
      "refer_link": "https://t.me/free_bot_host_bot?start=ref_123456789",
      "refer_count": 4,
      "api_key": "fbh_usr_...",
      "created_at": "2026-09-01 12:00:00"
    }
  }
  ```

---

#### 2. Wallet & Earnings

##### Get Wallet Balance & Transactions
- **Action**: `wallet` or `get_wallet`
- **Method**: `GET` / `POST`
- **Example**:
  ```http
  GET /user_api.php?action=get_wallet
  ```
- **Response**:
  ```json
  {
    "ok": true,
    "balance": 15.50,
    "balance_formatted": "15.50 USDT",
    "total_earnings": 25.00,
    "transactions": [
      {
        "id": 12,
        "type": "sale",
        "amount": 5.00,
        "status": "completed",
        "details": "Bot purchase commission",
        "created_at": "2026-09-15 14:20:00"
      }
    ]
  }
  ```

---

#### 3. Bots Management

##### List Hosted Bots
- **Action**: `list_bots`
- **Parameters**: `status` (optional: `all`, `active`, `deleted`)
- **Example**:
  ```http
  GET /user_api.php?action=list_bots
  ```

##### Get Bot Details
- **Action**: `get_bot`
- **Parameters**: `bot_id` (ID or `@username`)
- **Example**:
  ```http
  GET /user_api.php?action=get_bot&bot_id=10
  ```

##### Deploy / Create New Bot
- **Action**: `create_bot`
- **Method**: `POST`
- **Parameters**:
  - `token` (Required): BotFather token
  - `admin_chat_id` (Optional): Telegram ID of the bot admin
- **Example Body**:
  ```json
  {
    "action": "create_bot",
    "token": "1234567890:AAHxyz...",
    "admin_chat_id": "123456789"
  }
  ```

##### Soft-Delete Bot
- **Action**: `delete_bot`
- **Parameters**: `bot_id`

##### Restore Bot
- **Action**: `restore_bot`
- **Parameters**: `bot_id`

##### Restart Bot & Refresh Webhook
- **Action**: `restart_bot`
- **Parameters**: `bot_id`

##### Update Bot Token or Admin ID
- **Action**: `update_bot`
- **Parameters**: `bot_id`, `token` (optional), `admin_chat_id` (optional)

---

#### 4. File Manager & Code Editor

##### List Files & Directories
- **Action**: `list_files`
- **Parameters**:
  - `bot_id`: Target Bot ID
  - `path` (Optional): Subdirectory path (e.g. `handlers`)
- **Example**:
  ```http
  GET /user_api.php?action=list_files&bot_id=10&path=
  ```

##### Read File Content
- **Action**: `read_file`
- **Parameters**:
  - `bot_id`: Target Bot ID
  - `file`: Relative file path (e.g. `index.php` or `config.php`)
- **Example**:
  ```http
  GET /user_api.php?action=read_file&bot_id=10&file=index.php
  ```

##### Write / Save Code
- **Action**: `write_file`
- **Method**: `POST`
- **Parameters**:
  - `bot_id`: Target Bot ID
  - `file`: Relative file path
  - `content`: Code or file content
- **Features**: Automatic PHP syntax lint checking before saving; storage quota validation.

##### Create New File
- **Action**: `create_file`
- **Parameters**: `bot_id`, `name`, `path` (optional), `content` (optional)

##### Create New Folder
- **Action**: `create_folder`
- **Parameters**: `bot_id`, `name`, `path` (optional)

##### Delete File or Folder
- **Action**: `delete_file`
- **Parameters**: `bot_id`, `file`

##### Rename File or Folder
- **Action**: `rename_file`
- **Parameters**: `bot_id`, `old_path`, `new_name`

---

#### 5. Environment Variables (.env)

##### Get Bot Environment Variables
- **Action**: `get_env`
- **Parameters**: `bot_id`
- **Response**:
  ```json
  {
    "ok": true,
    "variables": {
      "DB_NAME": "storage/database.db",
      "API_SECRET": "secret123"
    },
    "raw": "DB_NAME=\"storage/database.db\"\nAPI_SECRET=\"secret123\"\n",
    "count": 2
  }
  ```

##### Set / Update Environment Variables
- **Action**: `set_env`
- **Method**: `POST`
- **Parameters**:
  - `bot_id`: Target Bot ID
  - `variables`: Key-value JSON object OR `content` as raw text string

---

#### 6. Cron Jobs Automation

##### List Cron Jobs
- **Action**: `list_crons`
- **Parameters**: `bot_id`

##### Create Cron Job
- **Action**: `create_cron`
- **Method**: `POST`
- **Parameters**:
  - `bot_id`: Target Bot ID
  - `script_path`: Relative PHP script path (e.g. `cron.php` or `tasks/backup.php`)
  - `name`: Descriptive job name
  - `interval_type`: `minutes`, `hourly`, `daily`, `weekly`, or `monthly`
  - `interval_minutes`: Interval duration if `interval_type` is `minutes`

##### Toggle Cron Job (Enable/Disable)
- **Action**: `toggle_cron`
- **Parameters**: `bot_id`, `cron_id`

##### Run Cron Job Now
- **Action**: `run_cron`
- **Parameters**: `bot_id`, `cron_id`
- **Returns**: Immediate output and execution logs.

##### Delete Cron Job
- **Action**: `delete_cron`
- **Parameters**: `bot_id`, `cron_id`

---

#### 7. Database Operations (SQLite)

Every bot has an isolated, high-speed SQLite database located at `storage/database.db`.

##### Get Database Schema & Tables
- **Action**: `db_info`
- **Parameters**: `bot_id`
- **Response**: Tables, column names, column types, row counts, and file size.

##### Execute Database Query
- **Action**: `db_query`
- **Method**: `POST`
- **Parameters**:
  - `bot_id`: Target Bot ID
  - `query`: SQL query statement (e.g. `SELECT * FROM users WHERE chat_id = ?`)
  - `params` (Optional): Prepared statement parameters array
- **Security**: Strictly sandboxed to the target bot's `database.db`. Host-level SQLite injection commands (e.g. `ATTACH`) are blocked.

---

#### 8. Broadcast Studio

##### Get Broadcast Statistics
- **Action**: `broadcast_stats`
- **Parameters**: `bot_id`
- **Response**: Total subscribers, active users in last 7 days, and recent broadcast history.

##### Launch Broadcast Message
- **Action**: `send_broadcast`
- **Method**: `POST`
- **Parameters**:
  - `bot_id`: Target Bot ID
  - `message`: Message text (supports HTML/Markdown formatting)
  - `audience`: `all` or `active7d`
  - `photo_url` (Optional): Image URL to attach
  - `keyboard` (Optional): Inline button matrix

---

#### 9. Bot Marketplace / Store

##### List Marketplace Bots
- **Action**: `list_store`
- **Parameters**: `search`, `category`, `price_type` (`all`, `free`, `paid`), `page`

##### Get Store Bot Details & Reviews
- **Action**: `store_details`
- **Parameters**: `store_id`

##### Install Store Bot
- **Action**: `install_store_bot`
- **Method**: `POST`
- **Parameters**: `store_id`, `token` (New BotFather token), `admin_chat_id`

---

#### 10. Bot Code Transfer System

Securely transfer bot source code between registered users without sharing credentials (`.env` keys and `database.db` are automatically sanitized and kept private).

##### Create Bot Transfer
- **Action**: `create_transfer`
- **Method**: `POST`
- **Parameters**:
  - `bot_id`: Bot ID to transfer
  - `target_recipient`: Telegram `@username` or numeric user ID of recipient
- **Returns**: A secure 72-hour transfer code (`TR-XXXX-XXXX`).
- **Example Body**:
  ```json
  {
    "action": "create_transfer",
    "bot_id": 12,
    "target_recipient": "@developer_user"
  }
  ```

##### List Transfers (Incoming & Outgoing)
- **Action**: `list_transfers` or `transfers`
- **Returns**: Pending incoming offers to accept and outgoing transfers you created.

##### Get Transfer Details
- **Action**: `get_transfer`
- **Parameters**: `transfer_code`
- **Returns**: Transfer status, bot name, sender handle, expiration timestamp.

##### Accept Bot Transfer
- **Action**: `accept_transfer`
- **Method**: `POST`
- **Parameters**:
  - `transfer_code`: Transfer code (e.g. `TR-12-34AB56CD`)
  - `token`: Your new Telegram bot token from @BotFather
  - `admin_chat_id` (Optional): Admin Telegram ID

##### Reject Bot Transfer
- **Action**: `reject_transfer`
- **Method**: `POST`
- **Parameters**: `transfer_id` (Numeric ID from `list_transfers`)

---

#### 11. Bot Building, Scaffolding, Validation & Webhook Testing

##### Get Bot Making Guide & Styled Keyboard Documentation
- **Action**: `bot_making_docs` or `get_bot_making_docs`
- **Method**: `GET` / `POST`
- **Parameters**: `section` (Optional: `keyboards`, `database`, `cron`, `broadcast`, `errors`, `examples`)
- **Returns**: Full markdown guide and button color mapping reference.

##### Scaffold Bot Code Boilerplate
- **Action**: `scaffold_bot` or `scaffold_bot_code`
- **Method**: `GET` / `POST`
- **Parameters**:
  - `type` (Optional: `styled_keyboard` [default], `database_bot`, `shop_bot`)
  - `bot_name` (Optional: e.g. `"CryptoTradeBot"`)
- **Returns**: Complete, production-ready, linted PHP source code with styled buttons.

##### Install Scaffold to Hosted Bot
- **Action**: `install_scaffold` or `install_bot_scaffold`
- **Method**: `POST`
- **Parameters**:
  - `bot_id`: Target hosted bot ID or username
  - `type`: Boilerplate type (`styled_keyboard`, `database_bot`, `shop_bot`)
- **Returns**: Overwrites `index.php` with the chosen scaffold and prepares storage.

##### Validate Bot PHP Code (Syntax & Lint Check)
- **Action**: `validate_code` or `validate_bot_code`
- **Method**: `POST`
- **Parameters**:
  - `code`: Raw PHP code string to lint
- **Returns**: Syntax verification result, detects missing semicolons, unbalanced brackets, syntax errors before deploying.

##### Simulate Webhook Update (Local Sandbox Test)
- **Action**: `test_webhook` or `test_bot_webhook`
- **Method**: `POST`
- **Parameters**:
  - `bot_id`: Target hosted bot ID or username
  - `update` (Optional): Simulated Telegram Update JSON object (defaults to `/start` message)
- **Returns**: Captures output buffered by `index.php`, HTTP response code, and fresh errors from `error.log`.

##### 🎨 Styled Keyboard Colors Reference
Telegram Mini Apps and modern Telegram bot clients support button style attributes:

| Style | Color | Use Cases |
| :--- | :--- | :--- |
| `primary` | **Blue** 🔵 | Main Actions, Launch App, Next, Open Menu, Confirm |
| `success` | **Green** 🟢 | Buy Now, Deposit, Pay, Approve, Activate |
| `danger`  | **Red** 🔴 | Delete, Cancel, Reset, Reject, Stop |

```php
// Inline Keyboard with Styles:
$inlineKeyboard = [
    'inline_keyboard' => [
        [
            ['text' => '🚀 Launch App', 'callback_data' => 'launch', 'style' => 'primary'], // Blue
            ['text' => '💳 Buy VIP', 'callback_data' => 'buy', 'style' => 'success']       // Green
        ],
        [
            ['text' => '❌ Cancel', 'callback_data' => 'cancel', 'style' => 'danger']       // Red
        ]
    ]
];
$reply_markup = json_encode($inlineKeyboard);

// Reply Keyboard with Styles:
$replyKeyboard = [
    'keyboard' => [
        [
            ['text' => '🟢 Activate Service', 'style' => 'success'],
            ['text' => '🔵 Account Dashboard', 'style' => 'primary']
        ],
        [
            ['text' => '🔴 Terminate Session', 'style' => 'danger']
        ]
    ],
    'resize_keyboard' => true
];
$reply_markup = json_encode($replyKeyboard);
```

---

#### 12. Botlify Knowledge Base & Documentation Engine (NEW)

##### 1. About Botlify Cloud (`action=about_botlify` or `action=about`)
Returns complete A-to-Z overview of Botlify Cloud architecture, runtime, SQLite WAL engine, webhook lifecycle, key features, and developer rules. Publicly accessible without API key.
- **Request:**
  `GET https://botlify.cloud/user_api.php?action=about_botlify`
- **Response:**
  ```json
  {
    "ok": true,
    "platform": {
      "name": "Botlify Cloud",
      "domain": "botlify.cloud",
      "tagline": "Enterprise Serverless Telegram Bot Hosting..."
    },
    "architecture": { ... },
    "how_it_works": { ... },
    "key_features": { ... },
    "developer_rules": { ... }
  }
  ```

##### 2. Get Full Documentation (`action=get_full_docs` or `action=full_docs`)
Retrieves the complete, unabridged master developer documentation (`docs/docs.md`, 1.08MB+, 14 chapters, all 203 methods & 401 types). Supports optional `offset` and `limit` for chunking.
- **Request:**
  `GET https://botlify.cloud/user_api.php?action=get_full_docs`
  `GET https://botlify.cloud/user_api.php?action=get_full_docs&offset=0&limit=5000`
- **Response:**
  ```json
  {
    "ok": true,
    "title": "Botlify Cloud — Master Production Developer Documentation...",
    "source": "docs/docs.md",
    "total_bytes": 1082293,
    "total_lines": 21500,
    "content": "# Botlify Cloud — Master Production..."
  }
  ```

##### 3. List Documentation Topics (`action=list_docs` or `action=docs`)
Returns all 638 documentation topics, categorized guides, Telegram Bot API methods, and types with their read times and canonical URLs.
- **Request:**
  `GET https://botlify.cloud/user_api.php?action=list_docs`
- **Response:**
  ```json
  {
    "ok": true,
    "total_docs": 638,
    "categories_summary": { ... },
    "docs": [
      {
        "id": "sendmessage",
        "title": "sendMessage",
        "category": "Telegram Bot API — Methods (A-Z)",
        "subtitle": "Send text messages with parse_mode and keyboards...",
        "url": "https://docs.botlify.cloud/sendmessage"
      }
    ]
  }
  ```

##### 4. Search Documentation (`action=search_docs` or `action=search`)
Performs scored keyword/phrase search across all documentation articles and methods with snippet extraction.
- **Request:**
  `GET https://botlify.cloud/user_api.php?action=search_docs&query=sendMessage&max_results=5`
- **Parameters:**
  - `query` (required): Search keyword or phrase.
  - `max_results` (optional, default 10, max 50): Number of matches to return.
- **Response:**
  ```json
  {
    "ok": true,
    "query": "sendMessage",
    "max_results": 5,
    "matched_count": 20,
    "results_count": 5,
    "results": [
      {
        "id": "sendmessage",
        "title": "sendMessage",
        "category": "Telegram Bot API — Methods (A-Z)",
        "snippet": "Use this method to send text messages...",
        "url": "https://docs.botlify.cloud/sendmessage"
      }
    ]
  }
  ```

---

### 💻 Code Examples

#### 1. cURL
```bash
curl -s -H "X-API-KEY: fbh_usr_your_api_key_here" \
  "https://your-domain.com/user_api.php?action=list_bots"

curl -s -H "X-API-KEY: fbh_usr_your_api_key_here" \
  "https://your-domain.com/user_api.php?action=read_file&bot_id=1&file=index.php"

curl -s -X POST "https://your-domain.com/user_api.php" \
  -H "X-API-KEY: fbh_usr_your_api_key_here" \
  -H "Content-Type: application/json" \
  -d '{
    "action": "write_file",
    "bot_id": 1,
    "file": "index.php",
    "content": "<?php\necho \"Hello from API!\";\n"
  }'
```

#### 2. Python (`requests`)
```python
import requests

API_KEY = "fbh_usr_your_api_key_here"
BASE_URL = "https://your-domain.com/user_api.php"
headers = {"X-API-KEY": API_KEY}

profile = requests.get(BASE_URL, headers=headers, params={"action": "profile"}).json()
print("Balance:", profile["user"]["balance_formatted"])

res = requests.post(BASE_URL, headers=headers, json={
    "action": "db_query",
    "bot_id": 1,
    "query": "SELECT chat_id, first_name FROM users LIMIT 5"
}).json()
print("Users:", res.get("rows", []))
```

#### 3. Node.js (`fetch`)
```javascript
const API_KEY = 'fbh_usr_your_api_key_here';
const BASE_URL = 'https://your-domain.com/user_api.php';

async function getBots() {
  const res = await fetch(`${BASE_URL}?action=list_bots`, {
    headers: { 'X-API-KEY': API_KEY }
  });
  const data = await res.json();
  console.log('My Bots:', data.bots);
}

getBots();
```

---

### ⚠️ Error Handling & Status Codes

| HTTP Status | Meaning | Typical Cause |
|-------------|---------|---------------|
| `200 OK` | Success | Operation completed successfully |
| `400 Bad Request` | Validation Error | Missing required parameter (e.g. missing `bot_id` or `token`) |
| `401 Unauthorized` | Invalid Key | API Key missing, invalid, or expired |
| `404 Not Found` | Resource Missing | Bot, file, or store item not found |
| `500 Server Error` | Execution Exception | File write permission issue or disk full |

---

## 7. 📢 Telegram Broadcast Ads & Analytics API (broadcast_api.php)

Welcome to the **Free Bot Host Broadcast & Ad Network API** (`digibd.store`). This API enables advertisers, bot developers, and network administrators to programmatically launch targeted ad broadcasts, estimate reachable audiences, manage flexible tracking links, and monitor real-time anti-fraud campaign performance across the Telegram bot network.

---

### 🌟 Key Architecture & Highlights

1. **Multi-Bot Network Dispatch (`target: bots`)**: Messages are sent directly through each hosted bot's own official Telegram bot token to its subscribed users.
2. **3 Flexible Link & Analytics Modes (`link_mode`)**:
   - **Option 1 (`link_mode: 1`)**: **Analytics URL + ulvis.net Shortener** — Clicks are tracked through `click.php` and shortened into compact `https://ulvis.net/xxxxxx` links.
   - **Option 2 (`link_mode: 2`)**: **Analytics URL Only** — Full tracking URL (`https://digibd.store/.../click.php?tid=xxxx`) without shortener.
   - **Option 3 (`link_mode: 3`)**: **Direct Real Link** — User's original destination URL is placed directly on buttons (no tracking proxy, CPM/click count N/A).
3. **Strict Anti-Fraud CPM Deduplication (1 IP = 1 Count)**:
   - Duplicate clicks from the same IP address are recorded as non-unique (`is_unique = 0`). Only distinct IP addresses increment the unique click count and CTR metrics.
4. **Strict Audience Quota Protection (`limit`)**: When specifying a `limit` (e.g. 1,000), if the available matching audience in the network is less than the requested limit (e.g. 450), the request is strictly **rejected** with a `400 Bad Request` error, returning `max_allowed_limit: 450` to protect advertiser payments against under-delivery.
5. **Audience Pre-Check & Estimator (`action=estimate`)**:
   - Estimate reachable users, active users today, 7-day activity, and language distributions *before* launching a campaign.
6. **Smart Recipient Deduplication (`deduplicate: true`)**:
   - When broadcasting across multiple hosted bots, users subscribed to more than one bot receive the message only **once** via their most active bot.
7. **Automated Dead Account Pruning (`blocked_cleaned`)**:
   - Detects users who blocked the bot or deleted their accounts in real-time, instantly prunes them from the database, and reports the count.
8. **Aggregated Privacy & Security**:
   - No sensitive raw IPs or user tokens are exposed in public reports or overviews.

---

### 7.1. 🔐 Authentication

All API requests must supply the authorized secret API key. You can provide it in any of three formats:

* **HTTP Header (Recommended)**: `X-API-KEY: SPDEV_BROCAST`
* **JSON Body Field**: `"api_key": "SPDEV_BROCAST"` or `"key": "SPDEV_BROCAST"`
* **Query Parameter**: `?api_key=SPDEV_BROCAST` or `?key=SPDEV_BROCAST`

---

### 7.2. 🌐 Base URL & Endpoints

```text
https://digibd.store/mybot/tgbothosts/brocast_api.php
```

| Action | HTTP Method | Purpose |
| :--- | :--- | :--- |
| `estimate` | `POST` / `GET` | Estimate audience size, active users today, and reachability before sending |
| `create` | `POST` | Launch a new broadcast ad campaign |
| `overview` / `status` | `GET` / `POST` | Get live delivery progress, unique clicks, CTR, device & country analytics |
| `stats` | `GET` / `POST` | Get platform-wide user counts, active users today, and global stats |
| `shorten` | `GET` / `POST` | Standalone URL shortening via ulvis.net API |

---

### 7.3. 📖 API Action Details

---

#### 3.1 Action: `estimate` (Audience & Reach Check)

Inspects database records according to your filters and calculates the exact matching audience size, today's active users, 7-day active users, and language breakdown without sending messages.

* **URL**: `https://digibd.store/mybot/tgbothosts/brocast_api.php?action=estimate`
* **Method**: `POST` or `GET`

##### Request Parameters:

| Parameter | Type | Required | Default | Description |
| :--- | :--- | :--- | :--- | :--- |
| `api_key` | string | Yes | — | `SPDEV_BROCAST` |
| `target` | string | No | `bots` | Audience scope: `bots`, `bot_owners`, `platform`, or `users`. |
| `active` | string | No | `""` (All) | Filter recency: `today` / `24h` / `1d`, `3d`, `7d`, `30d` / `1m`, `3m`, or `older`. |
| `joined` | string | No | `""` (All) | Filter registration date: `today`, `3d`, `7d`, `30d`. |
| `language` | string | No | `""` (All) | Language codes (e.g. `en`, `bn`, or comma-separated `en,bn,hi`). |
| `bot` | string | No | `""` | Target specific bot(s) by @username or bot ID (comma-separated supported). |
| `limit` | integer | No | `-1` | Target quota to check (`-1` for all available). |

##### cURL Example:
```bash
curl -X POST "https://digibd.store/mybot/tgbothosts/brocast_api.php" \
  -H "Content-Type: application/json" \
  -H "X-API-KEY: SPDEV_BROCAST" \
  -d '{
    "action": "estimate",
    "target": "bots",
    "active": "today",
    "language": "en,bn",
    "limit": 1000
  }'
```

##### Response Example:
```json
{
  "ok": true,
  "audience": {
    "available_targets": 1250,
    "requested_limit": 1000,
    "effective_queue_count": 1000,
    "is_sufficient": true,
    "active_today_sample": 450,
    "active_7d_sample": 920,
    "language_breakdown": {
      "en": 750,
      "bn": 500
    },
    "bots_involved_count": 12,
    "max_reach": 1250
  }
}
```

---

#### 3.2 Action: `create` (Launch Broadcast Campaign)

Creates, queues, and starts executing an ad broadcast. The initial chunk is processed synchronously, and remaining chunks run continuously in the background.

* **URL**: `https://digibd.store/mybot/tgbothosts/brocast_api.php?action=create`
* **Method**: `POST`
* **Content-Type**: `application/json` or `multipart/form-data` / `application/x-www-form-urlencoded`

##### Request Parameters:

| Parameter | Type | Required | Default | Description |
| :--- | :--- | :--- | :--- | :--- |
| `api_key` | string | Yes | — | `SPDEV_BROCAST` |
| `text` | string | Yes | — | Message text (HTML / Markdown). |
| `link_mode` | integer/string | No | `1` | **Link & Analytics Option**:<br>• `1` / `short`: Analytics URL + Shortener (Compact URL on button)<br>• `2` / `analytics`: Analytics URL Only (`https://digibd.store/.../click.php?tid=...`)<br>• `3` / `direct`: Direct Real Link (User's original destination link, CPM N/A) |
| `target` | string | No | `bots` | Audience Scope:<br>• `bots`: Users of all active hosted bots<br>• `bot_owners`: Creators/owners of hosted bots<br>• `platform`: Users of the main root host bot<br>• `users`: Specific Telegram Chat IDs |
| `adid` | string | No | `ad_{time}_{rand}` | Custom alphanumeric Campaign/Ad ID for tracking (e.g. `summer_sale_01`). |
| `limit` | integer | No | `-1` | **Target Delivery Quota**:<br>• `-1` (default): Send to **all available** matching users in the network.<br>• `0`: **Invalid** (returns `400 Bad Request`, minimum limit is 1).<br>• `> 0` (e.g. `500`): Limit delivery to exact user count. If requested limit exceeds total available matching users, the request is **rejected** with a `400 Bad Request` and returns `max_allowed_limit`. |
| `active` | string | No | `""` (All) | Filter activity: `today` / `24h` / `1d`, `3d`, `7d`, `30d` / `1m`, `3m`, or `older`. |
| `joined` | string | No | `""` (All) | Filter registration date: `today`, `3d`, `7d`, `30d`. |
| `language` | string | No | `""` (All) | Language filter: `en`, `bn`, or comma-separated list `en,bn,hi,ru`. |
| `bot` | string | No | `""` | Target specific bot(s) by @username or bot ID (comma-separated supported). |
| `deduplicate` | boolean | No | `true` | When `true` (default), ensures each Telegram user receives only 1 message across all bots. |
| `clean_blocked`| boolean | No | `true` | When `true` (default), automatically detects & prunes dead/blocked accounts from DB. When `false`, retains dead accounts in DB. |
| `user_ids` | string | No | `""` | Comma- or newline-separated Chat IDs (used when `target=users`). |
| `parse_mode` | string | No | `HTML` | Message formatting mode:<br>• `HTML` (default): `<b>bold</b>`, `<i>italic</i>`, `<code>code</code>`, `<a href="...">link</a>`<br>• `Markdown` / `md`: `*bold*`, `_italic_`, `` `code` ``, `[link](url)`<br>• `MarkdownV2` / `md2`: Advanced Telegram MarkdownV2 (`*bold*`, `_italic_`, `~strike~`, `\|\|spoiler\|\|`)<br>• `None` / `plain`: Plain text (formatting tags disabled) |
| `media_type` | string | No | `""` | Optional media: `photo`, `video`, `gif`, `animation`, `document`. |
| `media_file_id`| string | No | `""` | Telegram `file_id` or public `http://` / `https://` direct media URL. |
| `buttons` | array/string | No | `""` | Inline keyboard JSON array / string. |
| `inline_keyboard_builder` | string | No | `""` | Friendly button syntax: `Label \| URL` (comma for columns, newline for rows). |

---

##### Multi-Format Button Examples:

**Option A: JSON Array (Recommended for API integration)**:
```json
"buttons": [
  [{"text": "🔥 Claim 50% Off", "url": "https://digibd.store/deal"}],
  [{"text": "🤖 Start Bot", "url": "https://t.me/mybot"}, {"text": "💬 Support", "url": "https://t.me/support"}]
]
```

**Option B: Friendly Text Builder (Recommended for quick forms)**:
```text
inline_keyboard_builder=🔥 Claim 50% Off | https://digibd.store/deal
🤖 Start Bot | https://t.me/mybot , 💬 Support | https://t.me/support
```

---

##### Request Examples:

##### cURL (Option 1: Analytics + ulvis.net Short URL):
```bash
curl -X POST "https://digibd.store/mybot/tgbothosts/brocast_api.php" \
  -H "Content-Type: application/json" \
  -H "X-API-KEY: SPDEV_BROCAST" \
  -d '{
    "action": "create",
    "adid": "promo_premium_sale",
    "link_mode": 1,
    "target": "bots",
    "active": "today",
    "limit": 500,
    "parse_mode": "HTML",
    "text": "🚀 <b>MEGA PROMO ALERT!</b>",
    "buttons": [
      [{"text": "💬 Contact Support", "url": "https://t.me/sujoypaul"}]
    ]
  }'
```

##### cURL (Option 2: Analytics URL Only):
```bash
curl -X POST "https://digibd.store/mybot/tgbothosts/brocast_api.php" \
  -H "Content-Type: application/json" \
  -H "X-API-KEY: SPDEV_BROCAST" \
  -d '{
    "action": "create",
    "adid": "promo_analytics_only",
    "link_mode": 2,
    "target": "bots",
    "text": "📊 Check our analytics broadcast!",
    "buttons": [
      [{"text": "📊 View Offer", "url": "https://digibd.store/offer"}]
    ]
  }'
```

##### cURL (Option 3: Direct Real Link):
```bash
curl -X POST "https://digibd.store/mybot/tgbothosts/brocast_api.php" \
  -H "Content-Type: application/json" \
  -H "X-API-KEY: SPDEV_BROCAST" \
  -d '{
    "action": "create",
    "adid": "direct_announcement",
    "link_mode": 3,
    "target": "bots",
    "text": "📰 <b>Read our latest blog post!</b>",
    "buttons": [
      [{"text": "📖 Read Now", "url": "https://digibd.store/blog/post"}]
    ]
  }'
```

##### Response Example (Successful Campaign Creation):
```json
{
  "ok": true,
  "job_id": 5,
  "adid": "promo_premium_sale",
  "link_mode": 1,
  "link_mode_name": "Analytics + Short URL (ulvis.net)",
  "deduplicate": true,
  "deduplication_mode": "ON (1 message per unique user across all bots)",
  "clean_blocked": true,
  "auto_cleaning_mode": "ON (blocked accounts pruned from DB)",
  "available_matched_targets": 850,
  "requested_limit": 500,
  "queued_targets": 500,
  "processed_initial_chunk": 50,
  "status": "queued",
  "message": "Broadcast job created successfully."
}
```

##### Response Example (Insufficient Audience Rejection):
```json
{
  "ok": false,
  "error": "Insufficient audience: You requested 1000 users, but only 450 matching users are available in the network. Maximum limit you can set is 450.",
  "available_targets": 450,
  "requested_limit": 1000,
  "max_allowed_limit": 450,
  "is_sufficient": false
}
```

---

#### 3.3 Action: `overview` or `status` (Campaign Analytics & Performance)

Fetches live progress, delivery numbers, blocked account prunings, unique clicks, raw hits, Click-Through Rate (CTR), top devices, and top countries for a campaign.

* **URL**: `https://digibd.store/mybot/tgbothosts/brocast_api.php?action=overview`
* **Method**: `GET` or `POST`

##### Request Parameters:

| Parameter | Type | Required | Description |
| :--- | :--- | :--- | :--- |
| `api_key` | string | Yes | Must be `SPDEV_BROCAST`. |
| `adid` | string | No | The custom Campaign/Ad ID (e.g. `promo_premium_sale`). |
| `job_id` | integer | No | The internal broadcast job ID (e.g. `5`). |

*Either `adid` or `job_id` must be provided.*

##### Request Example (cURL):
```bash
curl "https://digibd.store/mybot/tgbothosts/brocast_api.php?api_key=SPDEV_BROCAST&action=overview&adid=promo_premium_sale"
```

##### Response Example (Option 1 & 2 - Tracked Campaign):
```json
{
  "ok": true,
  "job": {
    "id": 5,
    "adid": "promo_premium_sale",
    "scope": "bots",
    "link_mode": 1,
    "link_mode_name": "Analytics + Short URL (ulvis.net)",
    "tracking_enabled": true,
    "status": "done",
    "sent": 500,
    "failed": 12,
    "total": 500,
    "blocked_cleaned": 12,
    "clicks": 68,
    "unique_clicks": 68,
    "raw_hits": 94,
    "ctr_percent": 13.6,
    "device_breakdown": {
      "Android": 42,
      "iOS": 18,
      "Windows": 8
    },
    "country_breakdown": {
      "BD": 45,
      "IN": 15,
      "US": 8
    },
    "text_preview": "🚀 MEGA PROMO ALERT!...",
    "media_type": "text",
    "created_at": 1787062954,
    "time_ago": "12 mins ago"
  }
}
```

##### Response Example (Option 3 - Direct Real Link Campaign):
```json
{
  "ok": true,
  "job": {
    "id": 6,
    "adid": "direct_announcement",
    "scope": "bots",
    "link_mode": 3,
    "link_mode_name": "Direct Real Link",
    "tracking_enabled": false,
    "status": "done",
    "sent": 500,
    "failed": 8,
    "total": 500,
    "blocked_cleaned": 8,
    "clicks": "N/A",
    "unique_clicks": "N/A",
    "raw_hits": "N/A",
    "ctr_percent": "N/A",
    "tracking_notice": "Direct real link broadcast - click tracking and CPM analytics are not available for direct external URLs",
    "device_breakdown": {},
    "country_breakdown": {},
    "text_preview": "📰 Read our latest blog post!...",
    "media_type": "text",
    "created_at": 1787063500,
    "time_ago": "5 mins ago"
  }
}
```

---

#### 3.4 Action: `stats` (Global Platform Statistics)

Provides platform-wide metrics including total hosted bot registrations, unique human recipients, users active today, 7-day activity, and language distributions.

* **URL**: `https://digibd.store/mybot/tgbothosts/brocast_api.php?action=stats`
* **Method**: `GET` or `POST`

##### Request Example (cURL):
```bash
curl "https://digibd.store/mybot/tgbothosts/brocast_api.php?api_key=SPDEV_BROCAST&action=stats"
```

##### Response Example:
```json
{
  "ok": true,
  "stats": {
    "platform_users": 1580,
    "platform_active_24h": 420,
    "hosted_bot_users_total": 92300,
    "unique_hosted_bot_users": 68400,
    "active_bot_users_today": 12850,
    "active_bot_users_7d": 41200,
    "active_bots_count": 12,
    "total_ad_clicks": 4820,
    "unique_ad_clicks": 3950,
    "top_languages": {
      "en": 34000,
      "bn": 28000,
      "hi": 6400
    }
  }
}
```

---

#### 3.5 Action: `shorten` (Standalone ulvis.net Shortener)

Shortens any URL into a ulvis.net short link.

* **URL**: `https://digibd.store/mybot/tgbothosts/brocast_api.php?action=shorten&url=https://example.com`
* **Method**: `GET` or `POST`

##### Response Example:
```json
{
  "ok": true,
  "shorturl": "https://ulvis.net/27snebtr",
  "original_url": "https://example.com"
}
```

---

### 7.4. 💻 Full Multi-Language Code Integration Examples

#### Python (using `requests`)
```python
import requests

API_URL = "https://digibd.store/mybot/tgbothosts/brocast_api.php"
API_KEY = "SPDEV_BROCAST"
HEADERS = {"X-API-KEY": API_KEY, "Content-Type": "application/json"}

estimate_payload = {
    "action": "estimate",
    "target": "bots",
    "active": "today",
    "language": "en,bn",
    "limit": 1000
}
est = requests.post(API_URL, json=estimate_payload, headers=HEADERS).json()
print("Audience Estimate:", est["audience"])

create_payload = {
    "action": "create",
    "adid": "black_friday_deals",
    "link_mode": 1,
    "target": "bots",
    "active": "today",
    "limit": 1000,
    "parse_mode": "HTML",
    "text": "🔥 <b>BLACK FRIDAY SALE!</b>\nGet up to 70% off on premium bot hosting slots today!",
    "buttons": [
        [{"text": "🔥 Shop Deals Now", "url": "https://digibd.store/deals"}],
        [{"text": "🎁 Claim Bonus", "url": "https://digibd.store/bonus"}]
    ]
}
res = requests.post(API_URL, json=create_payload, headers=HEADERS).json()
print("Campaign Created:", res)

overview = requests.get(f"{API_URL}?api_key={API_KEY}&action=overview&adid=black_friday_deals").json()
print("Campaign Stats:", overview["job"])
```

---

#### Node.js / JavaScript (using `fetch`)
```javascript
const API_URL = "https://digibd.store/mybot/tgbothosts/brocast_api.php";
const API_KEY = "SPDEV_BROCAST";

async function runAdCampaign() {
  // 1. Audience Estimation
  const estRes = await fetch(API_URL, {
    method: "POST",
    headers: { "Content-Type": "application/json", "X-API-KEY": API_KEY },
    body: JSON.stringify({
      action: "estimate",
      target: "bots",
      active: "today",
      limit: 500
    })
  });
  const estData = await estRes.json();
  console.log("Reachable Audience:", estData.audience);

  // 2. Launch Campaign
  const createRes = await fetch(API_URL, {
    method: "POST",
    headers: { "Content-Type": "application/json", "X-API-KEY": API_KEY },
    body: JSON.stringify({
      action: "create",
      adid: "summer_special_2026",
      link_mode: 1, // 1: ulvis.net + Track, 2: Track Only, 3: Direct Link
      target: "bots",
      active: "today",
      limit: 500,
      parse_mode: "HTML",
      text: "⚡ <b>Exclusive VIP Hosting Offer!</b>\nFast servers and 99.9% uptime guaranteed.",
      buttons: [
        [{ text: "⚡ Get Started", url: "https://digibd.store/vip" }]
      ]
    })
  });
  const createData = await createRes.json();
  console.log("Broadcast Launched:", createData);

  // 3. Check Live Performance
  const overviewRes = await fetch(`${API_URL}?api_key=${API_KEY}&action=overview&adid=summer_special_2026`);
  const overviewData = await overviewRes.json();
  console.log("Campaign Stats:", overviewData.job);
}

runAdCampaign();
```

---

#### PHP (cURL Example)
```php
<?php
$apiUrl = "https://digibd.store/mybot/tgbothosts/brocast_api.php";
$apiKey = "SPDEV_BROCAST";

$payload = [
    'action'     => 'create',
    'adid'       => 'php_campaign_01',
    'link_mode'  => 1, // 1: ulvis.net + Analytics, 2: Analytics URL Only, 3: Direct Real Link
    'target'     => 'bots',
    'active'     => 'today',
    'language'   => 'en,bn',
    'limit'      => 250,
    'parse_mode' => 'HTML',
    'text'       => "🚀 <b>Hello from PHP!</b>\nCheck out our special bot hosting deals!",
    'buttons'    => [
        [['text' => '🔥 Claim Deal', 'url' => 'https://digibd.store/deal']]
    ]
];

$ch = curl_init($apiUrl);
curl_setopt_array($ch, [
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_POST           => true,
    CURLOPT_HTTPHEADER     => [
        "Content-Type: application/json",
        "X-API-KEY: $apiKey"
    ],
    CURLOPT_POSTFIELDS     => json_encode($payload)
]);
$res = curl_exec($ch);
curl_close($ch);

print_r(json_decode($res, true));
```

---

### 7.5. ⚠️ Error Responses & Troubleshooting

If an invalid request, insufficient audience (with strict limit), or invalid key is supplied, the API returns a structured JSON error:

```json
{
  "ok": false,
  "error": "Unauthorized: Invalid API Key"
}
```

| HTTP Code | Error Message | Solution / Cause |
| :--- | :--- | :--- |
| `403 Forbidden` | `Unauthorized: Invalid API Key` | Check that `api_key=SPDEV_BROCAST` or `X-API-KEY: SPDEV_BROCAST` is correctly passed. |
| `400 Bad Request` | `Missing parameter: text` | Ensure `text` message body is included in the `action=create` request. |
| `400 Bad Request` | `No target users match the specified filters.` | Your audience filter criteria matched 0 users. Check language or bot settings. |
| `400 Bad Request` | `Insufficient audience: You requested X users, but only Y matching users are available...` | Returned when requested `limit` exceeds available matching audience. Request is rejected to prevent payment under-delivery. Set `limit <= Y`. |
| `400 Bad Request` | `Missing parameter: job_id or adid` | Supply either `adid` or `job_id` when calling `overview` or `status`. |
| `404 Not Found` | `Job or Ad ID not found` | Verify that the specified `adid` or `job_id` exists in the system. |

---

## 8. 📰 Botlify Engineering Blog Engine & Blog REST API (blog/api.php)

The **Botlify Blog REST API** allows developers, Telegram bots, automated scripts, and CI/CD pipelines to programmatically read, publish, edit, and manage blog articles and categories on Botlify Cloud.

---

### 🔑 Authentication

Every request to the Blog API requires authentication using your **Blog API Key**. You can view or regenerate your API Key inside the **[Blog Studio Settings](https://botlify.cloud/blog/admin/?action=settings)**.

Authentication can be passed in any of the following 3 ways:

#### 1. HTTP Header (Recommended)
```http
X-Blog-Api-Key: btl_your_secret_api_key_here
```

#### 2. Bearer Token Header
```http
Authorization: Bearer btl_your_secret_api_key_here
```

#### 3. Query / Body Parameter (Fallback)
```http
https://botlify.cloud/blog/api.php?api_key=btl_your_secret_api_key_here&action=...
```

---

### 🌐 Base Endpoint

```
POST/GET https://botlify.cloud/blog/api.php
```

All responses are returned in JSON format with standard HTTP status codes:
- `200 OK` / `201 Created`: Request succeeded.
- `400 Bad Request`: Missing or invalid parameters.
- `401 Unauthorized`: Missing or incorrect API key.
- `404 Not Found`: Post or resource does not exist.
- `500 Server Error`: Database or internal exception.

---

### 📋 Endpoints & Actions Summary

| Action | HTTP Method | Description |
| :--- | :--- | :--- |
| `get_stats` | `GET` / `POST` | Retrieve total posts, published, drafts, views, categories, tags |
| `get_posts` | `GET` / `POST` | Fetch paginated list of posts with category, tag, or search filters |
| `get_post` | `GET` / `POST` | Retrieve a single post by `slug` or `id` |
| `create_post` | `POST` | Publish or draft a new article with Markdown & SEO metadata |
| `update_post` | `POST` | Update an existing post by `post_id` or `slug` |
| `delete_post` | `POST` | Permanently delete a post by `post_id` |
| `get_categories` | `GET` / `POST` | Get list of all categories with post counts |
| `upload_image` | `POST` | Upload an image file (PNG, JPG, WEBP, GIF, SVG) |

---

### 8.1. Get Blog Statistics

Fetch overall analytics including total published posts, drafts, and views.

#### Request:
```http
GET https://botlify.cloud/blog/api.php?action=get_stats
X-Blog-Api-Key: btl_your_secret_key
```

#### Response (`200 OK`):
```json
{
  "ok": true,
  "stats": {
    "total_posts": 12,
    "published_posts": 10,
    "draft_posts": 2,
    "total_views": 15420,
    "categories_count": 4,
    "tags_count": 18
  }
}
```

---

### 8.2. List Articles (`get_posts`)

Fetch a paginated list of articles.

#### Request Parameters:
| Parameter | Type | Required | Default | Description |
| :--- | :--- | :--- | :--- | :--- |
| `action` | string | **Yes** | `get_posts` | Action name |
| `page` | integer | No | `1` | Page number |
| `limit` | integer | No | `10` | Posts per page (max: 50) |
| `category` | string | No | `null` | Filter by category slug |
| `tag` | string | No | `null` | Filter by tag slug |
| `search` | string | No | `null` | Keyword search in title, excerpt, content |
| `include_drafts`| boolean | No | `false` | Include draft posts (1 or true) |

#### Example cURL:
```bash
curl -X GET "https://botlify.cloud/blog/api.php?action=get_posts&limit=5&category=guides-tutorials" \
     -H "X-Blog-Api-Key: btl_your_secret_key"
```

#### Response (`200 OK`):
```json
{
  "ok": true,
  "posts": [
    {
      "id": 1,
      "title": "How to Host a Telegram Bot 24/7 for Free: Complete Developer Guide (2026)",
      "slug": "how-to-host-telegram-bot-free-24-7",
      "excerpt": "Learn how to deploy, host, and keep your Telegram bot running 24/7 online for free...",
      "cover_image": "https://images.unsplash.com/photo-1618005182384-a83a8bd57fbe",
      "category_id": 1,
      "category_name": "Guides & Tutorials",
      "category_slug": "guides-tutorials",
      "author_name": "Botlify Cloud Team",
      "status": "published",
      "views": 1420,
      "is_featured": 1,
      "reading_time": 4,
      "created_at": 1740000000,
      "updated_at": 1740000000
    }
  ],
  "total": 1,
  "limit": 5,
  "offset": 0,
  "total_pages": 1,
  "current_page": 1
}
```

---

### 8.3. Get Single Article (`get_post`)

Fetch full post details including raw Markdown content, tags, and canonical URL.

#### Request:
```bash
curl -X GET "https://botlify.cloud/blog/api.php?action=get_post&slug=how-to-host-telegram-bot-free-24-7" \
     -H "X-Blog-Api-Key: btl_your_secret_key"
```

#### Response (`200 OK`):
```json
{
  "ok": true,
  "post": {
    "id": 1,
    "title": "How to Host a Telegram Bot 24/7 for Free: Complete Developer Guide (2026)",
    "slug": "how-to-host-telegram-bot-free-24-7",
    "excerpt": "Learn how to deploy, host, and keep your Telegram bot running 24/7...",
    "content": "# How to Host a Telegram Bot 24/7 for Free...",
    "cover_image": "https://images.unsplash.com/photo-1618005182384-a83a8bd57fbe",
    "category_name": "Guides & Tutorials",
    "category_slug": "guides-tutorials",
    "author_name": "Botlify Cloud Team",
    "status": "published",
    "views": 1421,
    "is_featured": 1,
    "reading_time": 4,
    "meta_title": "How to Host a Telegram Bot 24/7 for Free (2026 Guide) | Botlify Blog",
    "meta_description": "Complete step-by-step developer guide on hosting a 24/7 Telegram bot...",
    "meta_keywords": "host telegram bot free, telegram bot 24/7, botlify",
    "created_at": 1740000000,
    "tags": [
      { "id": 1, "name": "telegram-bot", "slug": "telegram-bot" },
      { "id": 2, "name": "bot-hosting", "slug": "bot-hosting" }
    ],
    "url": "https://botlify.cloud/blog/how-to-host-telegram-bot-free-24-7"
  }
}
```

---

### 8.4. Create Article (`create_post`)

Publish a new article with Markdown formatting, custom SEO tags, and categories.

#### Payload Fields:
| Field | Type | Required | Description |
| :--- | :--- | :--- | :--- |
| `title` | string | **Yes** | Article title |
| `content` | string | **Yes** | Article body in Markdown or HTML |
| `slug` | string | No | Custom URL slug (auto-generated from title if omitted) |
| `excerpt` | string | No | Short summary for cards and search snippets |
| `category_id` | integer | No | Numerical category ID |
| `category_slug`| string | No | Category slug (e.g. `telegram-bot-api`) |
| `cover_image` | string | No | Cover image URL |
| `author_name` | string | No | Author display name (Default: `Botlify Team`) |
| `status` | string | No | `published` (default) or `draft` |
| `is_featured` | integer | No | `1` for featured hero card, `0` otherwise |
| `tags` | string/array | No | Comma-separated tags or array (e.g. `"php, bot, webhooks"`) |
| `meta_title` | string | No | Custom title tag for Google SEO |
| `meta_description` | string | No | Custom meta description tag |
| `meta_keywords` | string | No | Comma-separated SEO keywords |

#### Example cURL (JSON):
```bash
curl -X POST "https://botlify.cloud/blog/api.php" \
     -H "Content-Type: application/json" \
     -H "X-Blog-Api-Key: btl_your_secret_key" \
     -d '{
       "action": "create_post",
       "title": "Deploying Telegram Mini Apps with Botlify Cloud",
       "excerpt": "A complete guide to hosting interactive HTML5 Telegram Mini Apps with SSL.",
       "category_slug": "telegram-bot-api",
       "cover_image": "https://images.unsplash.com/photo-1551288049-bebda4e38f71",
       "author_name": "Developer Advocate",
       "status": "published",
       "is_featured": 1,
       "tags": "miniapp, telegram, webhooks, javascript",
       "content": "# Deploying Telegram Mini Apps\n\nTelegram Mini Apps allow you to build rich JavaScript web apps inside Telegram chats.\n\n> [!TIP]\n> Botlify provides instant HTTPS for your Mini App webviews.\n\n```javascript\nwindow.Telegram.WebApp.ready();\n```"
     }'
```

#### Response (`201 Created`):
```json
{
  "ok": true,
  "message": "Post created successfully.",
  "post_id": 4,
  "slug": "deploying-telegram-mini-apps-with-botlify-cloud",
  "url": "https://botlify.cloud/blog/deploying-telegram-mini-apps-with-botlify-cloud"
}
```

---

### 8.5. Update Article (`update_post`)

Update an existing article using either its `post_id` or `slug`.

#### Example cURL:
```bash
curl -X POST "https://botlify.cloud/blog/api.php" \
     -H "Content-Type: application/json" \
     -H "X-Blog-Api-Key: btl_your_secret_key" \
     -d '{
       "action": "update_post",
       "post_id": 4,
       "title": "Deploying Telegram Mini Apps with Botlify Cloud (Updated)",
       "status": "published"
     }'
```

#### Response (`200 OK`):
```json
{
  "ok": true,
  "message": "Post updated successfully.",
  "post_id": 4,
  "slug": "deploying-telegram-mini-apps-with-botlify-cloud-updated",
  "url": "https://botlify.cloud/blog/deploying-telegram-mini-apps-with-botlify-cloud-updated"
}
```

---

### 8.6. Delete Article (`delete_post`)

Permanently delete an article.

#### Example cURL:
```bash
curl -X POST "https://botlify.cloud/blog/api.php" \
     -H "Content-Type: application/json" \
     -H "X-Blog-Api-Key: btl_your_secret_key" \
     -d '{
       "action": "delete_post",
       "post_id": 4
     }'
```

#### Response (`200 OK`):
```json
{
  "ok": true,
  "message": "Post deleted successfully."
}
```

---

### 8.7. Upload Image (`upload_image`)

Upload an image to Botlify Cloud storage (`/blog/uploads/`).

#### Supported formats:
`image/jpeg`, `image/png`, `image/webp`, `image/gif`, `image/svg+xml`.

#### Example cURL:
```bash
curl -X POST "https://botlify.cloud/blog/api.php?action=upload_image" \
     -H "X-Blog-Api-Key: btl_your_secret_key" \
     -F "image=@/path/to/my-cover.png"
```

#### Response (`200 OK`):
```json
{
  "ok": true,
  "url": "https://botlify.cloud/blog/uploads/api_img_20261029_141500_a1b2c3d4.png",
  "path": "/blog/uploads/api_img_20261029_141500_a1b2c3d4.png"
}
```

---

### 8.8. Code Examples

#### Python Example: Auto-Publishing a Blog Post
```python
import requests

API_URL = "https://botlify.cloud/blog/api.php"
API_KEY = "btl_your_secret_api_key_here"

headers = {
    "X-Blog-Api-Key": API_KEY,
    "Content-Type": "application/json"
}

payload = {
    "action": "create_post",
    "title": "Automated Deployment of Python Telegram Bots",
    "excerpt": "How to deploy Python Telegram bots with webhooks.",
    "category_slug": "telegram-bot-api",
    "tags": "python, bot, telegram, webhooks",
    "content": """# Python Bot Deployment Guide

Here is how to set up Python webhook bots:

```python
import telebot
bot = telebot.TeleBot("YOUR_TOKEN")
```

All requests are handled seamlessly on Botlify Cloud.
""",
    "status": "published"
}

response = requests.post(API_URL, json=payload, headers=headers)
print(response.json())
```

---

#### PHP Example: Publishing via Telegram Bot Command
```php
<?php
// Inside your Telegram bot webhook script
$text = $message['text'] ?? '';
$chatId = $message['chat']['id'];

if (str_starts_with($text, '/newblog ')) {
    $rawContent = trim(substr($text, 9));
    $lines = explode("\n", $rawContent, 2);
    $title = $lines[0];
    $body = $lines[1] ?? 'Content coming soon...';

    $ch = curl_init('https://botlify.cloud/blog/api.php');
    curl_setopt_array($ch, [
        CURLOPT_POST => true,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_HTTPHEADER => [
            'Content-Type: application/json',
            'X-Blog-Api-Key: btl_your_secret_api_key_here'
        ],
        CURLOPT_POSTFIELDS => json_encode([
            'action' => 'create_post',
            'title' => $title,
            'content' => $body,
            'status' => 'published'
        ])
    ]);
    
    $res = json_decode(curl_exec($ch), true);
    curl_close($ch);

    if (!empty($res['ok'])) {
        sendMessage($chatId, "✅ Post published successfully!\n🔗 " . $res['url']);
    } else {
        sendMessage($chatId, "❌ Failed to publish: " . ($res['error'] ?? 'Unknown error'));
    }
}
```

---

### 🔒 Security Best Practices

1. **Protect Your API Key:** Never commit your `btl_...` API key into public git repositories or share it with unauthorized users.
2. **Rotate Keys Regularly:** If a key is compromised, immediately click **Regenerate API Key** in [Blog Settings](https://botlify.cloud/blog/admin/?action=settings).
3. **Use HTTPS:** Always connect via `https://` to ensure authentication headers and payload contents remain encrypted in transit.

---

## 9. 📦 GitHub Automated Cloud Backup Engine (includes/github_backup.php)

Botlify Cloud features an enterprise automated cloud backup system designed to keep platform databases and file directories safely synchronized to a private GitHub repository on a scheduled interval.

### 🌟 Core Architectural Features

1. **Native MySQL Database Streaming Dumper (`github_backup_export_database`):**
   - Connects directly to the MySQL database configured in `config.php` (`DB_HOST`, `DB_NAME`, `DB_USER`, `DB_PASS`).
   - Streams complete table schemas (`SHOW CREATE TABLE`) and data (`INSERT INTO ... VALUES (...)`) directly to `database.sql`.
   - Pure PHP PDO streaming engine requiring **zero external `mysqldump` CLI dependencies**.
   - Transaction-safe with `SET FOREIGN_KEY_CHECKS=0;`, `SET AUTOCOMMIT=0;`, and `COMMIT;`.

2. **Selective Target Archiving (6 Configurable Targets):**
   - `database.sql`: MySQL live database export.
   - `ad_delete/`: Archived and soft-deleted bot scripts.
   - `assets/`: Platform stylesheets, JavaScript bundles, icons, and media files.
   - `blog/`: Full blog engine, Studio Admin, REST API, guides, and uploads.
   - `recycle/`: Platform recycle bin holding deleted bot workspaces.
   - `storage/`: User bot workspaces, sandboxes, and child SQLite databases (with recursion guards).

3. **Self-Healing Git Lock Recovery (`github_backup_clear_git_locks`):**
   - Automatically detects and unlinks any stale `.git/index.lock`, `HEAD.lock`, or `config.lock` before every Git stage (`git add`, `git commit`, `git push`).
   - If Git CLI ever throws `fatal: Unable to create 'index.lock': File exists`, the engine automatically clears the lock and retries the command smoothly.

4. **Central Master Cron Integration (`cron.php`):**
   - Hooked directly into the 1-minute central master cron runner (`cron.php`).
   - Configurable recurring intervals: Every 1 Hour, 2 Hours, 3 Hours, 6 Hours (Default), 12 Hours, 24 Hours, 48 Hours, or 72 Hours ("koy hour por por").
   - Executes non-interactively in the background without blocking bot webhook execution.

5. **Security & Token Masking:**
   - GitHub Personal Access Tokens (PAT) are masked in all execution logs and diagnostic outputs (`ghp_••••••••••••`).
   - Staging directory (`storage/.github_backup/`) is strictly ignored in the root `.gitignore` to prevent recursive repository bloat.

---

## 10. 🤖 Real-Time Dynamic LLMs.txt & AI Context Discovery (llms.php)

Botlify Cloud implements the open **https://llmstxt.org** standard to provide real-time, curated Markdown documentation to modern AI agents (Cursor, Windsurf, Claude 3.7 Sonnet, ChatGPT 4o, Google Gemini, Perplexity, Copilot, DeepSeek).

### Key Architectural Capabilities

- **Real-Time Dynamic Serving via Apache Rewrite:**
  - `https://botlify.cloud/llms.txt` ➔ Dynamic standard index (`llms.php`)
  - `https://botlify.cloud/llms-full.txt` ➔ Complete uncompressed knowledge base (`llms.php?mode=full`)
  - `https://botlify.cloud/blog/llms.txt` ➔ Dedicated blog engineering publications index (`llms.php?scope=blog`)
- **Live Database Querying:** Whenever an article is published or updated in the Blog Studio, `llms.php` immediately queries MySQL and serves the latest titles, slugs, reading times, categories, and direct REST API endpoints without requiring manual documentation rebuilds.
- **Conditional HTTP 304 Caching:** Emits `ETag` and `Cache-Control: public, max-age=120, stale-while-revalidate=60` headers, allowing AI crawlers to retrieve documentation at sub-10ms latency while keeping server load negligible.
- **Dual-Layer Disk Synchronization:** Whenever a blog post is saved or deleted, `botlify_sync_llms_files()` updates the static `llms.txt` and `llms-full.txt` fallbacks on disk.

---

## 11. 🗺️ Dynamic Real-Time XML Sitemaps & Discovery (sitemap.php)

Botlify Cloud provides real-time XML sitemaps and RSS 2.0 syndication feeds to guarantee instant search engine indexing and AI agent discoverability.

- **Platform Dynamic Sitemap:** `https://botlify.cloud/sitemap.xml` (rewritten to `sitemap.php`). Queries MySQL in real-time for all core pages, blog categories, and published articles.
- **Blog Dynamic Sitemap:** `https://botlify.cloud/blog/sitemap.xml` (via `blog/index.php?sitemap=1`). Dedicated sitemap with exact `<lastmod>` timestamps and weekly `<changefreq>`.
- **Blog RSS 2.0 Feed:** `https://botlify.cloud/blog/feed.xml` (via `blog/index.php?feed=rss`). Atom-linked RSS 2.0 syndication feed for newsletters, Telegram channels, and feed readers.
- **Discovery Header Links:** Both `<link rel="alternate" type="application/rss+xml" ...>` and `<link rel="alternate" type="text/markdown" ...>` are declared in the HTML `<head>` of all platform and blog pages.

---

## 12. ⚡ Complete Telegram Bot API Methods Reference (A-Z, 203 Methods)

This section provides the complete reference for all Telegram Bot API methods. Every method includes full descriptions, parameter definitions, and native PHP 8.2+ code examples.

### 12.1. Telegram Bot API: Overview

> How the Bot API works: requests, response envelope, webhooks vs polling, rate limits, formatting, and a map of the full method reference.

The **Telegram Bot API** is an HTTPS-based interface for controlling Telegram bots. Every method in this reference is an HTTPS request to:

```php
https://api.telegram.org/bot/METHOD_NAME
```

All method names are case-insensitive, and you can send parameters via URL query string, `application/json`, `application/x-www-form-urlencoded`, or `multipart/form-data`. Both GET and POST are supported.

#### Response Envelope

Every call returns a JSON object with the same envelope. Always check the `ok` flag before reading the result:

```php
{
    "ok": true,
    "result": { /* method-specific payload */ }
}
```

| Field | Type | Description |
| --- | --- | --- |
| ok | Boolean | True if the request succeeded |
| result | Any | The method-specific payload (a User object, a Message, True, …) |
| error_code | Integer | Present on failure — e.g. 400 (bad request), 401 (unauthorized), 429 (flood) |
| description | String | Human-readable description of the error |
| parameters | ResponseParameters | Optional hints, e.g. retry_after for flood control |

#### Calling Methods on Botlify Cloud

On Botlify Cloud your bot token is auto-injected as `BOT_TOKEN` in the per-bot `.env` file, and every bot ships with a global `bot()` helper that wraps the HTTP call and returns the decoded envelope:

```php

```

#### Sending Updates: Webhooks vs Long Polling

There are two mutually exclusive ways to receive updates from Telegram. On Botlify Cloud, **webhooks** are the recommended and default mode — the platform registers, secures, and routes the HTTPS webhook for you automatically.

| Mode | Method | Best For |
| --- | --- | --- |
| Webhook | setWebhook / deleteWebhook | Production — instant delivery, zero polling overhead. Diagnose with getWebhookInfo. |
| Long polling | getUpdates | Local development and scripts without a public URL. |

#### Rate Limits

- **30 messages per second** overall per bot. Broadcast in batches to stay under it.

- **~1 message per second** per chat (avoid bursts to the same chat).

- **~20 messages per minute** in the same group or channel.

- **Paid Broadcasts:** enable in @BotFather to raise the limit to **1,000 messages/second** for a fee of 0.1 Telegram Stars per message — pass `allow_paid_broadcast` on send methods.

- On `429` responses, wait the `retry_after` seconds before retrying.

#### Text Formatting

Messages accept **HTML** or **MarkdownV2** parse modes via the `parse_mode` parameter, and supports `message_effect_id` for animated full-screen effects in private chats. See the [Full-Screen Message Effects](/message-effects) guide for effect IDs.

#### Reference Directory

The method reference below is grouped by task. Start with these entry points:

| Sub-Group | What It Covers | Entry Point |
| --- | --- | --- |
| Auth & Session | Verify identity, log out, close the bot instance | getMe |
| Updates & Webhooks | Receive updates, register webhooks | setWebhook |
| Sending Messages & Media | All send* methods, forwards, copies, reactions, files | sendMessage |
| Edit & Manage Messages | Edit text/media/live locations, delete, stop polls | editMessageText |
| Callback, Inline & Mini Apps | Answer callbacks and inline queries, Web App flows | answerCallbackQuery |
| Chat Management | Members, admins, permissions, photos, titles, pins | getChatMember |
| Invites & Join Requests | Invite links, subscriptions, join request handling | createChatInviteLink |
| Forum Topics | Create and manage forum topics | createForumTopic |
| Bot Profile & Commands | Name, description, commands, menu button, admin rights | setMyCommands |
| Stickers & Emoji Sets | Create and manage sticker sets | createNewStickerSet |
| Payments & Telegram Stars | Invoices, receipts, Stars transactions and refunds | sendInvoice |
| Gifts & Verification | Send gifts, verify users and chats | sendGift |
| Business Accounts | Act on behalf of connected business accounts | getBusinessConnection |
| Stories | Post and manage stories | postStory |
| Games | Send games and submit scores | sendGame |
| Telegram Passport | Report Passport data errors | setPassportDataErrors |
| Managed Bots | Tokens and access for delegated bot management | getManagedBotToken |
| Guides & Tutorials | Task-focused Botlify guides with production code | 60-Second Quickstart |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 12.2. addStickerToSet

> Use this method to add a new sticker to a set created by the bot

Use this method to add a new sticker to a set created by the bot. Emoji sticker sets can have up to 200 stickers. Other sticker sets can have up to 120 stickers. Returns *True* on success.

#### Parameters

| Parameter | Type | Required | Description |
| --- | --- | --- | --- |
| user_id | Integer | Yes | User identifier of sticker set owner |
| name | String | Yes | Sticker set name |
| sticker | InputSticker | Yes | A JSON-serialized object with information about the added sticker. If exactly the same sticker had already been added to the set, then the set isn't changed. |

#### Example

```php

```

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 12.3. Animated Message Reactions

> React to incoming user messages with animated emojis (👍, 🔥, 🎉, ❤️, ⚡) using setMessageReaction.

#### The setMessageReaction Method

   

Telegram Bot API supports adding emoji reactions directly to user messages. This provides instant visual feedback before sending text replies.

   
```php
function react(string|int $chatId, int $messageId, string $emoji = '👍', bool $isBig = true): array {
    return bot('setMessageReaction', [
        'chat_id'    => $chatId,
        'message_id' => $messageId,
        'reaction'   => [
            ['type' => 'emoji', 'emoji' => $emoji]
        ],
        'is_big'     => $isBig
    ]);
}

// Usage Example on user message
if (!empty($msg['text'])) {
    react($chatId, $msg['message_id'], '🔥', true);
}
```

   

#### Popular Supported Emojis

   

Standard Unicode emojis supported by Telegram reactions: 👍, 👎, ❤️, 🔥, 🎉, 🤩, 👏, 😁, 🤔, 🤯, 😱, 🤬, 💩, ⚡, 🍌, 🍓, 🍾.

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 12.4. answerCallbackQuery

> Use this method to send answers to callback queries sent from inline keyboards

**Botlify Native Shorthand:**

  `tg_answer_cb($callbackQueryId, $text, $showAlert);`

  Dismisses button loading spinners instantly to avoid Telegram network timeouts. See [Native Helpers Guide](?page=tg-native-helpers).
 

Use this method to send answers to callback queries sent from inline keyboards. The answer will be displayed to the user as a notification at the top of the chat screen or as an alert. On success, *True* is returned.

Alternatively, the user can be redirected to the specified Game URL. For this option to work, you must first create a game for your bot via @BotFather and accept the terms. Otherwise, you may use links like `t.me/your_bot?start=XXXX` that open your bot with a parameter.

Otherwise, you may use links like `t.me/your_bot?start=XXXX` that open your bot with a parameter.

#### Parameters

| Parameter | Type | Required | Description |
| --- | --- | --- | --- |
| callback_query_id | String | Yes | Unique identifier for the query to be answered |
| text | String | Optional | Text of the notification. If not specified, nothing will be shown to the user, 0-200 characters. |
| show_alert | Boolean | Optional | If True, an alert will be shown by the client instead of a notification at the top of the chat screen. Defaults to False. |
| url | String | Optional | URL that will be opened by the user's client. If you have created a Game and accepted the conditions via @BotFather, specify the URL that opens your game - note that this will only work if the query comes from a callback_game button. |

#### Example

```php

```

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 12.5. answerChatJoinRequestQuery

> Use this method to process a received chat join request query

Use this method to process a received chat join request query. Returns *True* on success.

#### Parameters

| Parameter | Type | Required | Description |
| --- | --- | --- | --- |
| chat_join_request_query_id | String | Yes | Unique identifier of the join request query |
| result | String | Yes | Result of the query. Must be either "approve" to allow the user to join the chat, "decline" to disallow the user to join the chat, or "queue" to leave the decision to other administrators. |

#### Example

```php

```

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 12.6. answerGuestQuery

> Use this method to reply to a received guest message

Use this method to reply to a received guest message. On success, a SentGuestMessage object is returned.

#### Parameters

| Parameter | Type | Required | Description |
| --- | --- | --- | --- |
| guest_query_id | String | Yes | Unique identifier for the query to be answered |
| result | InlineQueryResult | Yes | A JSON-serialized object describing the message to be sent |

#### Example

```php

```

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 12.7. answerInlineQuery

> Use this method to send answers to an inline query

Use this method to send answers to an inline query. On success, *True* is returned.

No more than **50** results per query are allowed.

#### Parameters

| Parameter | Type | Required | Description |
| --- | --- | --- | --- |
| inline_query_id | String | Yes | Unique identifier for the answered query |
| results | Array of InlineQueryResult | Yes | A JSON-serialized Array of results for the inline query |
| cache_time | Integer | Optional | The maximum amount of time in seconds that the result of the inline query may be cached on the server. Defaults to 300. |
| is_personal | Boolean | Optional | Pass True if results may be cached on the server side only for the user that sent the query. By default, results may be returned to any user who sends the same query. |
| next_offset | String | Optional | Pass the offset that a client should send in the next query with the same text to receive more results. Pass an empty string if there are no more results or if you don't support pagination. Offset length can't exceed 64 bytes. |
| button | InlineQueryResultsButton | Optional | A JSON-serialized object describing a button to be shown above inline query results |

#### Example

```php

```

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 12.8. answerPreCheckoutQuery

> Once the user has confirmed their payment and shipping details, the Bot API sends the final confirmation in the form of an Update with the f

Once the user has confirmed their payment and shipping details, the Bot API sends the final confirmation in the form of an Update with the field *pre_checkout_query*. Use this method to respond to such pre-checkout queries. On success, *True* is returned. **Note:** The Bot API must receive an answer within 10 seconds after the pre-checkout query was sent.

#### Parameters

| Parameter | Type | Required | Description |
| --- | --- | --- | --- |
| pre_checkout_query_id | String | Yes | Unique identifier for the query to be answered |
| ok | Boolean | Yes | Specify True if everything is alright (goods are available, etc.) and the bot is ready to proceed with the order. Use False if there are any problems. |
| error_message | String | Optional | Required if ok is False. Error message in human readable form that explains the reason for failure to proceed with the checkout (e.g. "Sorry, somebody just bought the last of our amazing black T-shirts while you were busy filling out your payment details. Please choose a different color or garment!"). Telegram will display this message to the user. |

#### Example

```php

```

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 12.9. answerShippingQuery

> If you sent an invoice requesting a shipping address and the parameter *is_flexible* was specified, the Bot API will send an Update with a *

If you sent an invoice requesting a shipping address and the parameter *is_flexible* was specified, the Bot API will send an Update with a *shipping_query* field to the bot. Use this method to reply to shipping queries. On success, *True* is returned.

#### Parameters

| Parameter | Type | Required | Description |
| --- | --- | --- | --- |
| shipping_query_id | String | Yes | Unique identifier for the query to be answered |
| ok | Boolean | Yes | Pass True if delivery to the specified address is possible and False if there are any problems (for example, if delivery to the specified address is not possible) |
| shipping_options | Array of ShippingOption | Optional | Required if ok is True. A JSON-serialized Array of available shipping options. |
| error_message | String | Optional | Required if ok is False. Error message in human readable form that explains why it is impossible to complete the order (e.g. "Sorry, delivery to your desired address is unavailable"). Telegram will display this message to the user. |

#### Example

```php

```

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 12.10. answerWebAppQuery

> Use this method to set the result of an interaction with a Web App and send a corresponding message on behalf of the user to the chat from w

Use this method to set the result of an interaction with a Web App and send a corresponding message on behalf of the user to the chat from which the query originated. On success, a SentWebAppMessage object is returned.

#### Parameters

| Parameter | Type | Required | Description |
| --- | --- | --- | --- |
| web_app_query_id | String | Yes | Unique identifier for the query to be answered |
| result | InlineQueryResult | Yes | A JSON-serialized object describing the message to be sent |

#### Example

```php

```

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 12.11. approveChatJoinRequest

> Use this method to approve a chat join request

Use this method to approve a chat join request. The bot must be an administrator in the chat for this to work and must have the *can_invite_users* administrator right. Returns *True* on success.

#### Parameters

| Parameter | Type | Required | Description |
| --- | --- | --- | --- |
| chat_id | Integer or String | Yes | Unique identifier for the target chat or username of the target channel in the format @username |
| user_id | Integer | Yes | Unique identifier of the target user |

#### Example

```php

```

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 12.12. approveSuggestedPost

> Use this method to approve a suggested post in a direct messages chat

Use this method to approve a suggested post in a direct messages chat. The bot must have the 'can_post_messages' administrator right in the corresponding channel chat. Returns *True* on success.

#### Parameters

| Parameter | Type | Required | Description |
| --- | --- | --- | --- |
| chat_id | Integer | Yes | Unique identifier for the target direct messages chat |
| message_id | Integer | Yes | Identifier of a suggested post message to approve |
| send_date | Integer | Optional | Point in time (Unix timestamp) when the post is expected to be published; omit if the date has already been specified when the suggested post was created. If specified, then the date must be not more than 2678400 seconds (30 days) in the future. |

#### Example

```php

```

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 12.13. banChatMember

> Use this method to ban a user in a group, a supergroup or a channel

Use this method to ban a user in a group, a supergroup or a channel. In the case of supergroups and channels, the user will not be able to return to the chat on their own using invite links, etc., unless unbanned first. The bot must be an administrator in the chat for this to work and must have the appropriate administrator rights. Returns *True* on success.

#### Parameters

| Parameter | Type | Required | Description |
| --- | --- | --- | --- |
| chat_id | Integer or String | Yes | Unique identifier for the target group or username of the target supergroup or channel in the format @username |
| user_id | Integer | Yes | Unique identifier of the target user |
| until_date | Integer | Optional | Date when the user will be unbanned; Unix time. If user is banned for more than 366 days or less than 30 seconds from the current time they are considered to be banned forever. Applied for supergroups and channels only. |
| revoke_messages | Boolean | Optional | Pass True to delete all messages from the chat for the user that is being removed. If False, the user will be able to see messages in the group that were sent before the user was removed. Always True for supergroups and channels. |

#### Example

```php

```

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 12.14. banChatSenderChat

> Use this method to ban a channel chat in a supergroup or a channel

Use this method to ban a channel chat in a supergroup or a channel. Until the chat is unbanned, the owner of the banned chat won't be able to send messages on behalf of **any of their channels**. The bot must be an administrator in the supergroup or channel for this to work and must have the appropriate administrator rights. Returns *True* on success.

#### Parameters

| Parameter | Type | Required | Description |
| --- | --- | --- | --- |
| chat_id | Integer or String | Yes | Unique identifier for the target chat or username of the target channel in the format @username |
| sender_chat_id | Integer | Yes | Unique identifier of the target sender chat |

#### Example

```php

```

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 12.15. Bot Identity, Profile, Commands & Menu Button

> Inspect bot metadata (getMe), configure profile descriptions, command scopes, and the persistent [Menu] button.

#### Bot Identity & Metadata (getMe)

   

Before executing bot actions, you can query Telegram's servers to retrieve your bot's official identification, capabilities, and system flags using `getMe`:

   
```php

```

   
> [!TIP]
> **Auto-Injected Constant: BOT_USERNAME**
> On Botlify Cloud, you do not need to call getMe on every webhook to get your bot's handle. The platform automatically injects BOT_USERNAME directly into your .env file.

   

#### Customizing Bot Profile via API (Name, Bio & Description)

   

Telegram allows bots to programmatically configure their visible profile text without manually interacting with @BotFather:

   
    
| Method | Visibility in Telegram | Max Length |
| --- | --- | --- |
| setMyName | Top header title of the bot in chat lists and profile headers. | 64 characters |
| setMyDescription | Shown in the center of the screen when a user opens an empty chat with the bot before tapping /start. | 512 characters |
| setMyShortDescription | Shown on the bot's profile page and in Telegram chat share cards. | 120 characters |

   

   
```php

```

   

#### Registering Slash Commands with Granular Scopes

   

The `setMyCommands` method registers slash commands that autocomplete when users type `/`. Using Telegram's **BotCommandScope**, you can show different commands to normal users vs. chat administrators:

   
```php

```

   

#### Configuring the Persistent Bottom [Menu] Button

   

Telegram allows replacing the default paperclip or command menu button beside the chat input box with a direct **Web App Mini App** launcher using `setChatMenuButton`:

   
```php

```

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 12.16. Chat Join Requests & Auto-Approval

> Automatically approve or decline private channel and group join requests with instant welcome direct messages.

#### The chat_join_request Update

   

When users request to join private channels or invite-only groups, Telegram sends a `chat_join_request` update to your bot rather than a regular message.

   
```php
// Detect and Process Join Requests
if (isset($update['chat_join_request'])) {
    $req = $update['chat_join_request'];
    $chatId = $req['chat']['id'];
    $userId = $req['from']['id'];
    $userName = htmlspecialchars($req['from']['first_name'] ?? 'Friend', ENT_QUOTES, 'UTF-8');

    // 1. Instantly Approve the Join Request
    bot('approveChatJoinRequest', [
        'chat_id' => $chatId,
        'user_id' => $userId
    ]);

    // 2. Send Personalized Welcome Direct Message
    bot('sendMessage', [
        'chat_id'    => $userId,
        'text'       => "🎉 Welcome {$userName}!
Your request to join our channel has been automatically approved.",
        'parse_mode' => 'HTML',
        'reply_markup' => [
            'inline_keyboard' => [
                [['text' => '🚀 Launch Bot Dashboard', 'url' => 'https://t.me/' . BOT_USERNAME]]
            ]
        ]
    ]);

    exit('ok');
}
```

   

#### Decline Join Requests

   

If a user is banned or does not meet membership conditions, you can call `declineChatJoinRequest`:

   
```php
bot('declineChatJoinRequest', [
    'chat_id' => $chatId,
    'user_id' => $userId
]);
```

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 12.17. close

> Use this method to close the bot instance before moving it from one local server to another

Use this method to close the bot instance before moving it from one local server to another. You need to delete the webhook before calling this method to ensure that the bot isn't launched again after server restart. The method will return error 429 in the first 10 minutes after the bot is launched. Returns *True* on success. Requires no parameters.

#### Example

```php

```

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 12.18. closeForumTopic

> Use this method to close an open topic in a forum supergroup chat

Use this method to close an open topic in a forum supergroup chat. The bot must be an administrator in the chat for this to work and must have the *can_manage_topics* administrator rights, unless it is the creator of the topic. Returns *True* on success.

#### Parameters

| Parameter | Type | Required | Description |
| --- | --- | --- | --- |
| chat_id | Integer or String | Yes | Unique identifier for the target chat or username of the target supergroup in the format @username |
| message_thread_id | Integer | Yes | Unique identifier for the target message thread of the forum topic |

#### Example

```php

```

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 12.19. closeGeneralForumTopic

> Use this method to close an open 'General' topic in a forum supergroup chat

Use this method to close an open 'General' topic in a forum supergroup chat. The bot must be an administrator in the chat for this to work and must have the *can_manage_topics* administrator rights. Returns *True* on success.

#### Parameters

| Parameter | Type | Required | Description |
| --- | --- | --- | --- |
| chat_id | Integer or String | Yes | Unique identifier for the target chat or username of the target supergroup in the format @username |

#### Example

```php

```

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 12.20. Complete Master API Reference (A to Z)

> Comprehensive reference matrix covering all 100+ Telegram Bot API 8.x methods.

#### Alphabetical Methods Directory

   

The following table lists the most frequently implemented Telegram Bot API methods supported on Botlify Cloud:

   
    
| Method Name | HTTP Type | Description |
| --- | --- | --- |
| answerCallbackQuery | POST | Sends response to callback button tap to clear spinner. |
| approveChatJoinRequest | POST | Approves user request to join channel or group. |
| banChatMember | POST | Bans user from group, supergroup, or channel. |
| copyMessage / copyMessages | POST | Copies messages without link to original author. |
| createChatInviteLink | POST | Generates dynamic invite link with expiration/join limits. |
| createInvoiceLink | POST | Creates payment link for Telegram Stars or crypto invoices. |
| deleteMessage | POST | Deletes bot or user message in chat. |
| editMessageText | POST | Edits text and inline keyboard of existing message. |
| forwardMessage / forwardMessages | POST | Forwards messages from any chat. |
| getChatMember | POST | Checks user status in chat (crucial for Force-Subscribe). |
| getFile | POST | Retrieves file path for downloading photos, audio, documents. |
| getUserProfilePhotos | POST | Fetches user avatar profile pictures. |
| sendChatAction | POST | Shows 'typing...', 'upload_photo' indicators to users. |
| sendGift | POST | Sends Telegram digital gift to user or channel. |
| sendMessage | POST | Primary method to dispatch text messages with HTML/Markdown. |
| sendPhoto | POST | Sends images with optional caption and buttons. |
| sendSticker | POST | Sends animated (TGS), video (WEBM), or static stickers. |
| sendVideo | POST | Sends MP4 videos with custom cover and start timestamps. |
| setChatMenuButton | POST | Configures persistent bottom-left menu button in chat. |
| setMessageReaction | POST | Adds animated emoji reaction (👍, 🔥, ❤️) to message. |
| setMyCommands | POST | Registers slash command list for autocomplete popup. |

   

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 12.21. convertGiftToStars

> Converts a given regular gift to Telegram Stars

Converts a given regular gift to Telegram Stars. Requires the *can_convert_gifts_to_stars* business bot right. Returns *True* on success.

#### Parameters

| Parameter | Type | Required | Description |
| --- | --- | --- | --- |
| business_connection_id | String | Yes | Unique identifier of the business connection |
| owned_gift_id | String | Yes | Unique identifier of the regular gift that should be converted to Telegram Stars |

#### Example

```php

```

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 12.22. copyMessage

> Use this method to copy messages of any kind

Use this method to copy messages of any kind. Service messages, paid media messages, giveaway messages, giveaway winners messages, and invoice messages can't be copied. A quiz poll can be copied only if the value of the field *correct_option_ids* is known to the bot. The method is analogous to the method forwardMessage, but the copied message doesn't have a link to the original message. Returns the MessageId of the sent message on success.

#### Parameters

| Parameter | Type | Required | Description |
| --- | --- | --- | --- |
| chat_id | Integer or String | Yes | Unique identifier for the target chat or username of the target bot, supergroup or channel in the format @username |
| message_thread_id | Integer | Optional | Unique identifier for the target message thread (topic) of a forum; for forum supergroups and private chats of bots with forum topic mode enabled only |
| direct_messages_topic_id | Integer | Optional | Identifier of the direct messages topic to which the message will be sent; required if the message is sent to a direct messages chat |
| from_chat_id | Integer or String | Yes | Unique identifier for the chat where the original message was sent (or username of the target bot, supergroup or channel in the format @username) |
| message_id | Integer | Yes | Message identifier in the chat specified in from_chat_id |
| video_start_timestamp | Integer | Optional | New start timestamp for the copied video in the message |
| caption | String | Optional | New caption for media, 0-1024 characters after entities parsing. If not specified, the original caption is kept. |
| parse_mode | String | Optional | Mode for parsing entities in the new caption. See formatting options for more details. |
| caption_entities | Array of MessageEntity | Optional | A JSON-serialized list of special entities that appear in the new caption, which can be specified instead of parse_mode |
| show_caption_above_media | Boolean | Optional | Pass True if the caption must be shown above the message media. Ignored if a new caption isn't specified. |
| disable_notification | Boolean | Optional | Sends the message silently. Users will receive a notification with no sound. |
| protect_content | Boolean | Optional | Protects the contents of the sent message from forwarding and saving |
| allow_paid_broadcast | Boolean | Optional | Pass True to allow up to 1000 messages per second, ignoring broadcasting limits for a fee of 0.1 Telegram Stars per message. The relevant Stars will be withdrawn from the bot's balance. |
| message_effect_id | String | Optional | Unique identifier of the message effect to be added to the message; only available when copying to private chats |
| suggested_post_parameters | SuggestedPostParameters | Optional | A JSON-serialized object containing the parameters of the suggested post to send; for direct messages chats only. If the message is sent as a reply to another suggested post, then that suggested post is automatically declined. |
| reply_parameters | ReplyParameters | Optional | Description of the message to reply to |
| reply_markup | InlineKeyboardMarkup or ReplyKeyboardMarkup or ReplyKeyboardRemove or ForceReply | Optional | Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove a reply keyboard or to force a reply from the user. |

#### Example

```php

```

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 12.23. copyMessages

> Use this method to copy messages of any kind

Use this method to copy messages of any kind. If some of the specified messages can't be found or copied, they are skipped. Service messages, paid media messages, giveaway messages, giveaway winners messages, and invoice messages can't be copied. A quiz poll can be copied only if the value of the field *correct_option_ids* is known to the bot. The method is analogous to the method forwardMessages, but the copied messages don't have a link to the original message. Album grouping is kept for copied messages. On success, an Array of MessageId of the sent messages is returned.

#### Parameters

| Parameter | Type | Required | Description |
| --- | --- | --- | --- |
| chat_id | Integer or String | Yes | Unique identifier for the target chat or username of the target bot, supergroup or channel in the format @username |
| message_thread_id | Integer | Optional | Unique identifier for the target message thread (topic) of a forum; for forum supergroups and private chats of bots with forum topic mode enabled only |
| direct_messages_topic_id | Integer | Optional | Identifier of the direct messages topic to which the messages will be sent; required if the messages are sent to a direct messages chat |
| from_chat_id | Integer or String | Yes | Unique identifier for the chat where the original messages were sent (or username of the target bot, supergroup or channel in the format @username) |
| message_ids | Array of Integer | Yes | A JSON-serialized list of 1-100 identifiers of messages in the chat from_chat_id to copy. The identifiers must be specified in a strictly increasing order. |
| disable_notification | Boolean | Optional | Sends the messages silently. Users will receive a notification with no sound. |
| protect_content | Boolean | Optional | Protects the contents of the sent messages from forwarding and saving |
| remove_caption | Boolean | Optional | Pass True to copy the messages without their captions |

#### Example

```php

```

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 12.24. createChatInviteLink

> Use this method to create an additional invite link for a chat

Use this method to create an additional invite link for a chat. The bot must be an administrator in the chat for this to work and must have the appropriate administrator rights. The link can be revoked using the method revokeChatInviteLink. Returns the new invite link as ChatInviteLink object.

#### Parameters

| Parameter | Type | Required | Description |
| --- | --- | --- | --- |
| chat_id | Integer or String | Yes | Unique identifier for the target chat or username of the target channel in the format @username |
| name | String | Optional | Invite link name; 0-32 characters |
| expire_date | Integer | Optional | Point in time (Unix timestamp) when the link will expire |
| member_limit | Integer | Optional | The maximum number of users that can be members of the chat simultaneously after joining the chat via this invite link; 1-99999 |
| creates_join_request | Boolean | Optional | True, if users joining the chat via the link need to be approved by chat administrators. If True, member_limit can't be specified. |

#### Example

```php

```

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 12.25. createChatSubscriptionInviteLink

> Use this method to create a subscription invite link for a channel chat

Use this method to create a subscription invite link for a channel chat. The bot must have the *can_invite_users* administrator rights. The link can be edited using the method editChatSubscriptionInviteLink or revoked using the method revokeChatInviteLink. Returns the new invite link as a ChatInviteLink object.

#### Parameters

| Parameter | Type | Required | Description |
| --- | --- | --- | --- |
| chat_id | Integer or String | Yes | Unique identifier for the target channel chat or username of the target channel in the format @username |
| name | String | Optional | Invite link name; 0-32 characters |
| subscription_period | Integer | Yes | The number of seconds the subscription will be active for before the next payment. Currently, it must always be 2592000 (30 days). |
| subscription_price | Integer | Yes | The amount of Telegram Stars a user must pay initially and after each subsequent subscription period to be a member of the chat; 1-10000 |

#### Example

```php

```

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 12.26. createForumTopic

> Use this method to create a topic in a forum supergroup chat or a private chat with a user

Use this method to create a topic in a forum supergroup chat or a private chat with a user. In the case of a supergroup chat the bot must be an administrator in the chat for this to work and must have the *can_manage_topics* administrator right. Returns information about the created topic as a ForumTopic object.

#### Parameters

| Parameter | Type | Required | Description |
| --- | --- | --- | --- |
| chat_id | Integer or String | Yes | Unique identifier for the target chat or username of the target supergroup in the format @username |
| name | String | Yes | Topic name, 1-128 characters |
| icon_color | Integer | Optional | Color of the topic icon in RGB format. Currently, must be one of 7322096 (0x6FB9F0), 16766590 (0xFFD67E), 13338331 (0xCB86DB), 9367192 (0x8EEE98), 16749490 (0xFF93B2), or 16478047 (0xFB6F5F). |
| icon_custom_emoji_id | String | Optional | Unique identifier of the custom emoji shown as the topic icon. Use getForumTopicIconStickers to get all allowed custom emoji identifiers. |

#### Example

```php

```

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 12.27. createInvoiceLink

> Use this method to create a link for an invoice

Use this method to create a link for an invoice. Returns the created invoice link as *String* on success.

#### Parameters

| Parameter | Type | Required | Description |
| --- | --- | --- | --- |
| business_connection_id | String | Optional | Unique identifier of the business connection on behalf of which the link will be created. For payments in Telegram Stars only. |
| title | String | Yes | Product name, 1-32 characters |
| description | String | Yes | Product description, 1-255 characters |
| payload | String | Yes | Bot-defined invoice payload, 1-128 bytes. This will not be displayed to the user, use it for your internal processes. |
| provider_token | String | Optional | Payment provider token, obtained via @BotFather. Pass an empty string for payments in Telegram Stars. |
| currency | String | Yes | Three-letter ISO 4217 currency code, see more on currencies. Pass "XTR" for payments in Telegram Stars. |
| prices | Array of LabeledPrice | Yes | Price breakdown, a JSON-serialized list of components (e.g. product price, tax, discount, delivery cost, delivery tax, bonus, etc.). Must contain exactly one item for payments in Telegram Stars. |
| subscription_period | Integer | Optional | The number of seconds the subscription will be active for before the next payment. The currency must be set to "XTR" (Telegram Stars) if the parameter is used. Currently, it must always be 2592000 (30 days) if specified. Any number of subscriptions can be active for a given bot at the same time, including multiple concurrent subscriptions from the same user. Subscription price must no exceed 10000 Telegram Stars. |
| max_tip_amount | Integer | Optional | The maximum accepted amount for tips in the smallest units of the currency (integer, not float/double). For example, for a maximum tip of US$ 1.45 pass max_tip_amount = 145. See the exp parameter in currencies.json, it shows the number of digits past the decimal point for each currency (2 for the majority of currencies). Defaults to 0. Not supported for payments in Telegram Stars. |
| suggested_tip_amounts | Array of Integer | Optional | A JSON-serialized Array of suggested amounts of tips in the smallest units of the currency (integer, not float/double). At most 4 suggested tip amounts can be specified. The suggested tip amounts must be positive, passed in a strictly increased order and must not exceed max_tip_amount. |
| provider_data | String | Optional | JSON-serialized data about the invoice, which will be shared with the payment provider. A detailed description of required fields should be provided by the payment provider. |
| photo_url | String | Optional | URL of the product photo for the invoice. Can be a photo of the goods or a marketing image for a service. |
| photo_size | Integer | Optional | Photo size in bytes |
| photo_width | Integer | Optional | Photo width |
| photo_height | Integer | Optional | Photo height |
| need_name | Boolean | Optional | Pass True if you require the user's full name to complete the order. Ignored for payments in Telegram Stars. |
| need_phone_number | Boolean | Optional | Pass True if you require the user's phone number to complete the order. Ignored for payments in Telegram Stars. |
| need_email | Boolean | Optional | Pass True if you require the user's email address to complete the order. Ignored for payments in Telegram Stars. |
| need_shipping_address | Boolean | Optional | Pass True if you require the user's shipping address to complete the order. Ignored for payments in Telegram Stars. |
| send_phone_number_to_provider | Boolean | Optional | Pass True if the user's phone number should be sent to the provider. Ignored for payments in Telegram Stars. |
| send_email_to_provider | Boolean | Optional | Pass True if the user's email address should be sent to the provider. Ignored for payments in Telegram Stars. |
| is_flexible | Boolean | Optional | Pass True if the final price depends on the shipping method. Ignored for payments in Telegram Stars. |

#### Example

```php

```

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 12.28. createNewStickerSet

> Use this method to create a new sticker set owned by a user

Use this method to create a new sticker set owned by a user. The bot will be able to edit the sticker set thus created. Returns *True* on success.

#### Parameters

| Parameter | Type | Required | Description |
| --- | --- | --- | --- |
| user_id | Integer | Yes | User identifier of created sticker set owner |
| name | String | Yes | Short name of sticker set, to be used in t.me/addstickers/ URLs (e.g., animals). Can contain only English letters, digits and underscores. Must begin with a letter, can't contain consecutive underscores and must end in "_by_".  is case insensitive. 1-64 characters. |
| title | String | Yes | Sticker set title, 1-64 characters |
| stickers | Array of InputSticker | Yes | A JSON-serialized list of 1-50 initial stickers to be added to the sticker set |
| sticker_type | String | Optional | Type of stickers in the set, pass "regular", "mask", or "custom_emoji". By default, a regular sticker set is created. |
| needs_repainting | Boolean | Optional | Pass True if stickers in the sticker set must be repainted to the color of text when used in messages, the accent color if used as emoji status, white on chat photos, or another appropriate color based on context; for custom emoji sticker sets only |

#### Example

```php

```

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 12.29. declineChatJoinRequest

> Use this method to decline a chat join request

Use this method to decline a chat join request. The bot must be an administrator in the chat for this to work and must have the *can_invite_users* administrator right. Returns *True* on success.

#### Parameters

| Parameter | Type | Required | Description |
| --- | --- | --- | --- |
| chat_id | Integer or String | Yes | Unique identifier for the target chat or username of the target channel in the format @username |
| user_id | Integer | Yes | Unique identifier of the target user |

#### Example

```php

```

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 12.30. declineSuggestedPost

> Use this method to decline a suggested post in a direct messages chat

Use this method to decline a suggested post in a direct messages chat. The bot must have the 'can_manage_direct_messages' administrator right in the corresponding channel chat. Returns *True* on success.

#### Parameters

| Parameter | Type | Required | Description |
| --- | --- | --- | --- |
| chat_id | Integer | Yes | Unique identifier for the target direct messages chat |
| message_id | Integer | Yes | Identifier of a suggested post message to decline |
| comment | String | Optional | Comment for the creator of the suggested post; 0-128 characters |

#### Example

```php

```

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 12.31. deleteAllMessageReactions

> Use this method to remove up to 10000 recent reactions in a group or a supergroup chat added by a given user or chat

Use this method to remove up to 10000 recent reactions in a group or a supergroup chat added by a given user or chat. The bot must have the 'can_delete_messages' administrator right in the chat. Returns *True* on success.

#### Parameters

| Parameter | Type | Required | Description |
| --- | --- | --- | --- |
| chat_id | Integer or String | Yes | Unique identifier for the target chat or username of the target supergroup in the format @username |
| user_id | Integer | Optional | Identifier of the user whose reactions will be removed, if the reactions were added by a user |
| actor_chat_id | Integer | Optional | Identifier of the chat whose reactions will be removed, if the reactions were added by a chat |

#### Example

```php

```

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 12.32. deleteBusinessMessages

> Delete messages on behalf of a business account

Delete messages on behalf of a business account. Requires the *can_delete_sent_messages* business bot right to delete messages sent by the bot itself, or the *can_delete_all_messages* business bot right to delete any message. Returns *True* on success.

#### Parameters

| Parameter | Type | Required | Description |
| --- | --- | --- | --- |
| business_connection_id | String | Yes | Unique identifier of the business connection on behalf of which to delete the messages |
| message_ids | Array of Integer | Yes | A JSON-serialized list of 1-100 identifiers of messages to delete. All messages must be from the same chat. See deleteMessage for limitations on which messages can be deleted. |

#### Example

```php

```

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 12.33. deleteChatPhoto

> Use this method to delete a chat photo

Use this method to delete a chat photo. Photos can't be changed for private chats. The bot must be an administrator in the chat for this to work and must have the appropriate administrator rights. Returns *True* on success.

#### Parameters

| Parameter | Type | Required | Description |
| --- | --- | --- | --- |
| chat_id | Integer or String | Yes | Unique identifier for the target chat or username of the target channel in the format @username |

#### Example

```php

```

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 12.34. deleteChatStickerSet

> Use this method to delete a group sticker set from a supergroup

Use this method to delete a group sticker set from a supergroup. The bot must be an administrator in the chat for this to work and must have the appropriate administrator rights. Use the field *can_set_sticker_set* optionally returned in getChat requests to check if the bot can use this method. Returns *True* on success.

#### Parameters

| Parameter | Type | Required | Description |
| --- | --- | --- | --- |
| chat_id | Integer or String | Yes | Unique identifier for the target chat or username of the target supergroup in the format @username |

#### Example

```php

```

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 12.35. deleteEphemeralMessage

> Use this method to delete an ephemeral message

Use this method to delete an ephemeral message. Note that it is not guaranteed that the user will receive the message deletion event, especially if they are offline. Returns *True* on success.

#### Parameters

| Parameter | Type | Required | Description |
| --- | --- | --- | --- |
| chat_id | Integer or String | Yes | Unique identifier for the target chat or username of the target supergroup in the format @username |
| receiver_user_id | Integer | Yes | Identifier of the user who received the message |
| ephemeral_message_id | Integer | Yes | Identifier of the ephemeral message to delete |

#### Example

```php

```

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 12.36. deleteForumTopic

> Use this method to delete a forum topic along with all its messages in a forum supergroup chat or a private chat with a user

Use this method to delete a forum topic along with all its messages in a forum supergroup chat or a private chat with a user. In the case of a supergroup chat the bot must be an administrator in the chat for this to work and must have the *can_delete_messages* administrator rights. Returns *True* on success.

#### Parameters

| Parameter | Type | Required | Description |
| --- | --- | --- | --- |
| chat_id | Integer or String | Yes | Unique identifier for the target chat or username of the target supergroup in the format @username |
| message_thread_id | Integer | Yes | Unique identifier for the target message thread of the forum topic |

#### Example

```php

```

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 12.37. deleteMessage

> Use this method to delete a message, including service messages, with the following limitations: - A message can only be deleted if it was s

**Botlify Native Shorthand:**

  `tg_delete($chatId, $messageId);`

  Deletes a message instantly from any chat or channel. See [Native Helpers Guide](?page=tg-native-helpers).
 

Use this method to delete a message, including service messages, with the following limitations:

- A message can only be deleted if it was sent less than 48 hours ago.

- Service messages about a supergroup, channel, or forum topic creation can't be deleted.

- A dice message in a private chat can only be deleted if it was sent more than 24 hours ago.

- Bots can delete outgoing messages in private chats, groups, and supergroups.

- Bots can delete incoming messages in private chats.

- Bots granted *can_post_messages* permissions can delete outgoing messages in channels.

- If the bot is an administrator of a group, it can delete any message there.

- If the bot has *can_delete_messages* administrator right in a supergroup or a channel, it can delete any message there.

- If the bot has *can_manage_direct_messages* administrator right in a channel, it can delete any message in the corresponding direct messages chat.

Returns *True* on success.

#### Parameters

| Parameter | Type | Required | Description |
| --- | --- | --- | --- |
| chat_id | Integer or String | Yes | Unique identifier for the target chat or username of the target bot, supergroup or channel in the format @username |
| message_id | Integer | Yes | Identifier of the message to delete |

#### Example

```php

```

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 12.38. deleteMessageReaction

> Use this method to remove a reaction from a message in a group or a supergroup chat

Use this method to remove a reaction from a message in a group or a supergroup chat. The bot must have the 'can_delete_messages' administrator right in the chat. Returns *True* on success.

#### Parameters

| Parameter | Type | Required | Description |
| --- | --- | --- | --- |
| chat_id | Integer or String | Yes | Unique identifier for the target chat or username of the target supergroup in the format @username |
| message_id | Integer | Yes | Identifier of the target message |
| user_id | Integer | Optional | Identifier of the user whose reaction will be removed, if the reaction was added by a user |
| actor_chat_id | Integer | Optional | Identifier of the chat whose reaction will be removed, if the reaction was added by a chat |

#### Example

```php

```

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 12.39. deleteMessages

> Use this method to delete multiple messages simultaneously

Use this method to delete multiple messages simultaneously. If some of the specified messages can't be found, they are skipped. Returns *True* on success.

#### Parameters

| Parameter | Type | Required | Description |
| --- | --- | --- | --- |
| chat_id | Integer or String | Yes | Unique identifier for the target chat or username of the target bot, supergroup or channel in the format @username |
| message_ids | Array of Integer | Yes | A JSON-serialized list of 1-100 identifiers of messages to delete. See deleteMessage for limitations on which messages can be deleted. |

#### Example

```php

```

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 12.40. deleteMyCommands

> Use this method to delete the list of the bot's commands for the given scope and user language

Use this method to delete the list of the bot's commands for the given scope and user language. After deletion, higher level commands will be shown to affected users. Returns *True* on success.

#### Parameters

| Parameter | Type | Required | Description |
| --- | --- | --- | --- |
| scope | BotCommandScope | Optional | A JSON-serialized object, describing scope of users for which the commands are relevant. Defaults to BotCommandScopeDefault. |
| language_code | String | Optional | A two-letter ISO 639-1 language code. If empty, commands will be applied to all users from the given scope, for whose language there are no dedicated commands. |

#### Example

```php

```

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 12.41. deleteStickerFromSet

> Use this method to delete a sticker from a set created by the bot

Use this method to delete a sticker from a set created by the bot. Returns *True* on success.

#### Parameters

| Parameter | Type | Required | Description |
| --- | --- | --- | --- |
| sticker | String | Yes | File identifier of the sticker |

#### Example

```php

```

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 12.42. deleteStickerSet

> Use this method to delete a sticker set that was created by the bot

Use this method to delete a sticker set that was created by the bot. Returns *True* on success.

#### Parameters

| Parameter | Type | Required | Description |
| --- | --- | --- | --- |
| name | String | Yes | Sticker set name |

#### Example

```php

```

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 12.43. deleteStory

> Deletes a story previously posted by the bot on behalf of a managed business account

Deletes a story previously posted by the bot on behalf of a managed business account. Requires the *can_manage_stories* business bot right. Returns *True* on success.

#### Parameters

| Parameter | Type | Required | Description |
| --- | --- | --- | --- |
| business_connection_id | String | Yes | Unique identifier of the business connection |
| story_id | Integer | Yes | Unique identifier of the story to delete |

#### Example

```php

```

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 12.44. deleteWebhook

> Use this method to remove webhook integration if you decide to switch back to getUpdates

Use this method to remove webhook integration if you decide to switch back to getUpdates. Returns *True* on success.

#### Parameters

| Parameter | Type | Required | Description |
| --- | --- | --- | --- |
| drop_pending_updates | Boolean | Optional | Pass True to drop all pending updates |

#### Example

```php

```

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 12.45. editChatInviteLink

> Use this method to edit a non-primary invite link created by the bot

Use this method to edit a non-primary invite link created by the bot. The bot must be an administrator in the chat for this to work and must have the appropriate administrator rights. Returns the edited invite link as a ChatInviteLink object.

#### Parameters

| Parameter | Type | Required | Description |
| --- | --- | --- | --- |
| chat_id | Integer or String | Yes | Unique identifier for the target chat or username of the target channel in the format @username |
| invite_link | String | Yes | The invite link to edit |
| name | String | Optional | Invite link name; 0-32 characters |
| expire_date | Integer | Optional | Point in time (Unix timestamp) when the link will expire |
| member_limit | Integer | Optional | The maximum number of users that can be members of the chat simultaneously after joining the chat via this invite link; 1-99999 |
| creates_join_request | Boolean | Optional | True, if users joining the chat via the link need to be approved by chat administrators. If True, member_limit can't be specified. |

#### Example

```php

```

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 12.46. editChatSubscriptionInviteLink

> Use this method to edit a subscription invite link created by the bot

Use this method to edit a subscription invite link created by the bot. The bot must have the *can_invite_users* administrator rights. Returns the edited invite link as a ChatInviteLink object.

#### Parameters

| Parameter | Type | Required | Description |
| --- | --- | --- | --- |
| chat_id | Integer or String | Yes | Unique identifier for the target chat or username of the target channel in the format @username |
| invite_link | String | Yes | The invite link to edit |
| name | String | Optional | Invite link name; 0-32 characters |

#### Example

```php

```

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 12.47. editEphemeralMessageCaption

> Use this method to edit the caption of an ephemeral message

Use this method to edit the caption of an ephemeral message. Note that it is not guaranteed that the user will receive the message edit event, especially if they are offline. On success, *True* is returned.

#### Parameters

| Parameter | Type | Required | Description |
| --- | --- | --- | --- |
| chat_id | Integer or String | Yes | Unique identifier for the target chat or username of the target supergroup in the format @username |
| receiver_user_id | Integer | Yes | Identifier of the user who received the message |
| ephemeral_message_id | Integer | Yes | Identifier of the ephemeral message to edit |
| caption | String | Optional | New caption of the message, 0-1024 characters after entities parsing |
| parse_mode | String | Optional | Mode for parsing entities in the message caption. See formatting options for more details. |
| caption_entities | Array of MessageEntity | Optional | A JSON-serialized list of special entities that appear in the caption, which can be specified instead of parse_mode |
| show_caption_above_media | Boolean | Optional | Pass True if the caption must be shown above the message media. Supported only for animation, photo and video messages. |
| reply_markup | InlineKeyboardMarkup | Optional | A JSON-serialized object for an inline keyboard |

#### Example

```php

```

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 12.48. editEphemeralMessageMedia

> Use this method to edit the media of an ephemeral message

Use this method to edit the media of an ephemeral message. Note that it is not guaranteed that the user will receive the message edit event, especially if they are offline. On success, *True* is returned.

#### Parameters

| Parameter | Type | Required | Description |
| --- | --- | --- | --- |
| chat_id | Integer or String | Yes | Unique identifier for the target chat or username of the target supergroup in the format @username |
| receiver_user_id | Integer | Yes | Identifier of the user who received the message |
| ephemeral_message_id | Integer | Yes | Identifier of the ephemeral message to edit |
| media | InputMedia | Yes | A JSON-serialized object for the new media content of the message |
| reply_markup | InlineKeyboardMarkup | Optional | A JSON-serialized object for an inline keyboard |

#### Example

```php

```

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 12.49. editEphemeralMessageReplyMarkup

> Use this method to edit only the reply markup of an ephemeral message

Use this method to edit only the reply markup of an ephemeral message. Note that it is not guaranteed that the user will receive the message edit event, especially if they are offline. On success, *True* is returned.

#### Parameters

| Parameter | Type | Required | Description |
| --- | --- | --- | --- |
| chat_id | Integer or String | Yes | Unique identifier for the target chat or username of the target supergroup in the format @username |
| receiver_user_id | Integer | Yes | Identifier of the user who received the message |
| ephemeral_message_id | Integer | Yes | Identifier of the ephemeral message to edit |
| reply_markup | InlineKeyboardMarkup | Optional | A JSON-serialized object for an inline keyboard |

#### Example

```php

```

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 12.50. editEphemeralMessageText

> Use this method to edit an ephemeral text or rich message

Use this method to edit an ephemeral text or rich message. Note that it is not guaranteed that the user will receive the message edit event, especially if they are offline. On success, *True* is returned.

#### Parameters

| Parameter | Type | Required | Description |
| --- | --- | --- | --- |
| chat_id | Integer or String | Yes | Unique identifier for the target chat or username of the target supergroup in the format @username |
| receiver_user_id | Integer | Yes | Identifier of the user who received the message |
| ephemeral_message_id | Integer | Yes | Identifier of the ephemeral message to edit |
| text | String | Optional | New text of the message, 1-4096 characters after entity parsing; required if rich_message isn't specified |
| parse_mode | String | Optional | Mode for parsing entities in the message text. See formatting options for more details. |
| entities | Array of MessageEntity | Optional | A JSON-serialized list of special entities that appear in message text, which can be specified instead of parse_mode |
| rich_message | InputRichMessage | Optional | New rich content of the message; required if text isn't specified |
| link_preview_options | LinkPreviewOptions | Optional | Link preview generation options for the message |
| reply_markup | InlineKeyboardMarkup | Optional | A JSON-serialized object for an inline keyboard |

#### Example

```php

```

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 12.51. editForumTopic

> Use this method to edit name and icon of a topic in a forum supergroup chat or a private chat with a user

Use this method to edit name and icon of a topic in a forum supergroup chat or a private chat with a user. In the case of a supergroup chat the bot must be an administrator in the chat for this to work and must have the *can_manage_topics* administrator rights, unless it is the creator of the topic. Returns *True* on success.

#### Parameters

| Parameter | Type | Required | Description |
| --- | --- | --- | --- |
| chat_id | Integer or String | Yes | Unique identifier for the target chat or username of the target supergroup in the format @username |
| message_thread_id | Integer | Yes | Unique identifier for the target message thread of the forum topic |
| name | String | Optional | New topic name, 0-128 characters. If not specified or empty, the current name of the topic will be kept. |
| icon_custom_emoji_id | String | Optional | New unique identifier of the custom emoji shown as the topic icon. Use getForumTopicIconStickers to get all allowed custom emoji identifiers. Pass an empty string to remove the icon. If not specified, the current icon will be kept. |

#### Example

```php

```

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 12.52. editGeneralForumTopic

> Use this method to edit the name of the 'General' topic in a forum supergroup chat

Use this method to edit the name of the 'General' topic in a forum supergroup chat. The bot must be an administrator in the chat for this to work and must have the *can_manage_topics* administrator rights. Returns *True* on success.

#### Parameters

| Parameter | Type | Required | Description |
| --- | --- | --- | --- |
| chat_id | Integer or String | Yes | Unique identifier for the target chat or username of the target supergroup in the format @username |
| name | String | Yes | New topic name, 1-128 characters |

#### Example

```php

```

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 12.53. editMessageCaption

> Use this method to edit captions of messages

Use this method to edit captions of messages. On success, if the edited message is not an inline message, the edited Message is returned, otherwise *True* is returned. Note that business messages that were not sent by the bot and do not contain an inline keyboard can only be edited within **48 hours** from the time they were sent.

#### Parameters

| Parameter | Type | Required | Description |
| --- | --- | --- | --- |
| business_connection_id | String | Optional | Unique identifier of the business connection on behalf of which the message to be edited was sent |
| chat_id | Integer or String | Optional | Required if inline_message_id is not specified. Unique identifier for the target chat or username of the target bot, supergroup or channel in the format @username. |
| message_id | Integer | Optional | Required if inline_message_id is not specified. Identifier of the message to edit. |
| inline_message_id | String | Optional | Required if chat_id and message_id are not specified. Identifier of the inline message. |
| caption | String | Optional | New caption of the message, 0-1024 characters after entities parsing |
| parse_mode | String | Optional | Mode for parsing entities in the message caption. See formatting options for more details. |
| caption_entities | Array of MessageEntity | Optional | A JSON-serialized list of special entities that appear in the caption, which can be specified instead of parse_mode |
| show_caption_above_media | Boolean | Optional | Pass True if the caption must be shown above the message media. Supported only for animation, photo and video messages. |
| reply_markup | InlineKeyboardMarkup | Optional | A JSON-serialized object for an inline keyboard |

#### Example

```php

```

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 12.54. editMessageChecklist

> Use this method to edit a checklist on behalf of a connected business account

Use this method to edit a checklist on behalf of a connected business account. On success, the edited Message is returned.

#### Parameters

| Parameter | Type | Required | Description |
| --- | --- | --- | --- |
| business_connection_id | String | Yes | Unique identifier of the business connection on behalf of which the message will be sent |
| chat_id | Integer or String | Yes | Unique identifier for the target chat or username of the target bot in the format @username |
| message_id | Integer | Yes | Unique identifier for the target message |
| checklist | InputChecklist | Yes | A JSON-serialized object for the new checklist |
| reply_markup | InlineKeyboardMarkup | Optional | A JSON-serialized object for the new inline keyboard for the message |

#### Example

```php

```

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 12.55. editMessageLiveLocation

> Use this method to edit live location messages

Use this method to edit live location messages. A location can be edited until its *live_period* expires or editing is explicitly disabled by a call to stopMessageLiveLocation. On success, if the edited message is not an inline message, the edited Message is returned, otherwise *True* is returned.

#### Parameters

| Parameter | Type | Required | Description |
| --- | --- | --- | --- |
| business_connection_id | String | Optional | Unique identifier of the business connection on behalf of which the message to be edited was sent |
| chat_id | Integer or String | Optional | Required if inline_message_id is not specified. Unique identifier for the target chat or username of the target bot, supergroup or channel in the format @username. |
| message_id | Integer | Optional | Required if inline_message_id is not specified. Identifier of the message to edit. |
| inline_message_id | String | Optional | Required if chat_id and message_id are not specified. Identifier of the inline message. |
| latitude | Float | Yes | Latitude of new location |
| longitude | Float | Yes | Longitude of new location |
| live_period | Integer | Optional | New period in seconds during which the location can be updated, starting from the message send date. If 0x7FFFFFFF is specified, then the location can be updated forever. Otherwise, the new value must not exceed the current live_period by more than a day, and the live location expiration date must remain within the next 90 days. If not specified, then live_period remains unchanged. |
| horizontal_accuracy | Float | Optional | The radius of uncertainty for the location, measured in meters; 0-1500 |
| heading | Integer | Optional | Direction in which the user is moving, in degrees. Must be between 1 and 360 if specified. |
| proximity_alert_radius | Integer | Optional | The maximum distance for proximity alerts about approaching another chat member, in meters. Must be between 1 and 100000 if specified. |
| reply_markup | InlineKeyboardMarkup | Optional | A JSON-serialized object for a new inline keyboard |

#### Example

```php

```

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 12.56. editMessageMedia

> Use this method to edit animation, audio, document, live photo, photo, or video messages, or to replace a text or a rich message with a media

Use this method to edit animation, audio, document, live photo, photo, or video messages, or to replace a text or a rich message with a media. If a message is part of a message album, then it can be edited only to an audio for audio albums, only to a document for document albums and to a photo, a live photo, or a video otherwise. When an inline message is edited, a new file can't be uploaded; use a previously uploaded file via its file_id or specify a URL. On success, if the edited message is not an inline message, the edited Message is returned, otherwise *True* is returned. Note that business messages that were not sent by the bot and do not contain an inline keyboard can only be edited within **48 hours** from the time they were sent.

#### Parameters

| Parameter | Type | Required | Description |
| --- | --- | --- | --- |
| business_connection_id | String | Optional | Unique identifier of the business connection on behalf of which the message to be edited was sent |
| chat_id | Integer or String | Optional | Required if inline_message_id is not specified. Unique identifier for the target chat or username of the target bot, supergroup or channel in the format @username. |
| message_id | Integer | Optional | Required if inline_message_id is not specified. Identifier of the message to edit. |
| inline_message_id | String | Optional | Required if chat_id and message_id are not specified. Identifier of the inline message. |
| media | InputMedia | Yes | A JSON-serialized object for the new media content of the message |
| reply_markup | InlineKeyboardMarkup | Optional | A JSON-serialized object for a new inline keyboard |

#### Example

```php

```

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 12.57. editMessageReplyMarkup

> Use this method to edit only the reply markup of messages

Use this method to edit only the reply markup of messages. On success, if the edited message is not an inline message, the edited Message is returned, otherwise *True* is returned. Note that business messages that were not sent by the bot and do not contain an inline keyboard can only be edited within **48 hours** from the time they were sent.

#### Parameters

| Parameter | Type | Required | Description |
| --- | --- | --- | --- |
| business_connection_id | String | Optional | Unique identifier of the business connection on behalf of which the message to be edited was sent |
| chat_id | Integer or String | Optional | Required if inline_message_id is not specified. Unique identifier for the target chat or username of the target bot, supergroup or channel in the format @username. |
| message_id | Integer | Optional | Required if inline_message_id is not specified. Identifier of the message to edit. |
| inline_message_id | String | Optional | Required if chat_id and message_id are not specified. Identifier of the inline message. |
| reply_markup | InlineKeyboardMarkup | Optional | A JSON-serialized object for an inline keyboard |

#### Example

```php

```

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 12.58. editMessageText

> Use this method to edit text, rich and game messages

**Botlify Native Shorthand:**

  `tg_edit($chatId, $messageId, $newText, $extra);`

  Edits text messages in-place with zero boilerplate in 1 line. See [Native Helpers Guide](?page=tg-native-helpers).
 

Use this method to edit text, rich and game messages. On success, if the edited message is not an inline message, the edited Message is returned, otherwise *True* is returned. Note that business messages that were not sent by the bot and do not contain an inline keyboard can only be edited within **48 hours** from the time they were sent.

#### Parameters

| Parameter | Type | Required | Description |
| --- | --- | --- | --- |
| business_connection_id | String | Optional | Unique identifier of the business connection on behalf of which the message to be edited was sent |
| chat_id | Integer or String | Optional | Required if inline_message_id is not specified. Unique identifier for the target chat or username of the target bot, supergroup or channel in the format @username. |
| message_id | Integer | Optional | Required if inline_message_id is not specified. Identifier of the message to edit. |
| inline_message_id | String | Optional | Required if chat_id and message_id are not specified. Identifier of the inline message. |
| text | String | Optional | New text of the message, 1-4096 characters after entity parsing; required if rich_message isn't specified |
| parse_mode | String | Optional | Mode for parsing entities in the message text. See formatting options for more details. |
| entities | Array of MessageEntity | Optional | A JSON-serialized list of special entities that appear in message text, which can be specified instead of parse_mode |
| link_preview_options | LinkPreviewOptions | Optional | Link preview generation options for the message |
| rich_message | InputRichMessage | Optional | New rich content of the message; required if text isn't specified. Direct upload of new files and explicit upload of files by a URL isn't supported when an inline message is edited. |
| reply_markup | InlineKeyboardMarkup | Optional | A JSON-serialized object for an inline keyboard |

#### Example

```php

```

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 12.59. editStory

> Edits a story previously posted by the bot on behalf of a managed business account

Edits a story previously posted by the bot on behalf of a managed business account. Requires the *can_manage_stories* business bot right. Returns Story on success.

#### Parameters

| Parameter | Type | Required | Description |
| --- | --- | --- | --- |
| business_connection_id | String | Yes | Unique identifier of the business connection |
| story_id | Integer | Yes | Unique identifier of the story to edit |
| content | InputStoryContent | Yes | Content of the story |
| caption | String | Optional | Caption of the story, 0-2048 characters after entities parsing |
| parse_mode | String | Optional | Mode for parsing entities in the story caption. See formatting options for more details. |
| caption_entities | Array of MessageEntity | Optional | A JSON-serialized list of special entities that appear in the caption, which can be specified instead of parse_mode |
| areas | Array of StoryArea | Optional | A JSON-serialized list of clickable areas to be shown on the story |

#### Example

```php

```

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 12.60. editUserStarSubscription

> Allows the bot to cancel or re-enable extension of a subscription paid in Telegram Stars

Allows the bot to cancel or re-enable extension of a subscription paid in Telegram Stars. Returns *True* on success.

#### Parameters

| Parameter | Type | Required | Description |
| --- | --- | --- | --- |
| user_id | Integer | Yes | Identifier of the user whose subscription will be edited |
| telegram_payment_charge_id | String | Yes | Telegram payment identifier for the subscription |
| is_canceled | Boolean | Yes | Pass True to cancel extension of the user subscription; the subscription must be active up to the end of the current subscription period. Pass False to allow the user to re-enable a subscription that was previously canceled by the bot. |

#### Example

```php

```

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 12.61. exportChatInviteLink

> Use this method to generate a new primary invite link for a chat; any previously generated primary link is revoked

Use this method to generate a new primary invite link for a chat; any previously generated primary link is revoked. The bot must be an administrator in the chat for this to work and must have the appropriate administrator rights. Returns the new invite link as *String* on success.

#### Parameters

| Parameter | Type | Required | Description |
| --- | --- | --- | --- |
| chat_id | Integer or String | Yes | Unique identifier for the target chat or username of the target channel in the format @username |

#### Example

```php

```

> [!NOTE]
> **Official Notes**
> Note: Each administrator in a chat generates their own invite links. Bots can't use invite links generated by other administrators. If you want your bot to work with invite links, it will need to generate its own link using exportChatInviteLink or by calling the getChat method. If your bot needs to generate a new primary invite link replacing its previous one, use exportChatInviteLink again.

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 12.62. Forum Topics & Supergroups (message_thread_id)

> Create, edit, close, and organize Telegram Forum topics, manage custom icon colors, and route updates via message_thread_id.

#### Telegram Forum Supergroups Overview

   

Telegram allows large supergroups to enable **Topics**, transforming single chat streams into threaded sub-forums (e.g. *#General*, *#Announcements*, *#Support*). Every topic has a unique `message_thread_id` (which equals the `message_id` of the topic creation action).

   
> [!TIP]
> **How Thread Routing Works**
> To send or reply to a message inside a specific topic, you simply supply 'message_thread_id' => $threadId in your sendMessage, sendPhoto, or sendDocument payload. If omitted, messages are posted to the General topic.

   

#### 1. Creating Forum Topics Programmatically (createForumTopic)

   

Bots can programmatically spawn new discussion topics for customer tickets, project alerts, or product categories:

   
```php

```

   

#### 2. Routing Incoming Messages Within Forum Threads

   

When users post messages in a forum supergroup, Telegram includes `message_thread_id` in the incoming webhook. Always capture and preserve this ID when responding:

   
```php

```

   

#### 3. Editing, Closing, Reopening & Deleting Topics

   

When tickets are resolved or projects complete, bots can close or archive the topic:

   
```php

```

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 12.63. forwardMessage

> Use this method to forward messages of any kind

Use this method to forward messages of any kind. Service messages and messages with protected content can't be forwarded. On success, the sent Message is returned.

#### Parameters

| Parameter | Type | Required | Description |
| --- | --- | --- | --- |
| chat_id | Integer or String | Yes | Unique identifier for the target chat or username of the target bot, supergroup or channel in the format @username |
| message_thread_id | Integer | Optional | Unique identifier for the target message thread (topic) of a forum; for forum supergroups and private chats of bots with forum topic mode enabled only |
| direct_messages_topic_id | Integer | Optional | Identifier of the direct messages topic to which the message will be forwarded; required if the message is forwarded to a direct messages chat |
| from_chat_id | Integer or String | Yes | Unique identifier for the chat where the original message was sent (or username of the target bot, supergroup or channel in the format @username) |
| video_start_timestamp | Integer | Optional | New start timestamp for the forwarded video in the message |
| disable_notification | Boolean | Optional | Sends the message silently. Users will receive a notification with no sound. |
| protect_content | Boolean | Optional | Protects the contents of the forwarded message from forwarding and saving |
| message_effect_id | String | Optional | Unique identifier of the message effect to be added to the message; only available when forwarding to private chats |
| suggested_post_parameters | SuggestedPostParameters | Optional | A JSON-serialized object containing the parameters of the suggested post to send; for direct messages chats only |
| message_id | Integer | Yes | Message identifier in the chat specified in from_chat_id |

#### Example

```php

```

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 12.64. forwardMessages

> Use this method to forward multiple messages of any kind

Use this method to forward multiple messages of any kind. If some of the specified messages can't be found or forwarded, they are skipped. Service messages and messages with protected content can't be forwarded. Album grouping is kept for forwarded messages. On success, an Array of MessageId of the sent messages is returned.

#### Parameters

| Parameter | Type | Required | Description |
| --- | --- | --- | --- |
| chat_id | Integer or String | Yes | Unique identifier for the target chat or username of the target bot, supergroup or channel in the format @username |
| message_thread_id | Integer | Optional | Unique identifier for the target message thread (topic) of a forum; for forum supergroups and private chats of bots with forum topic mode enabled only |
| direct_messages_topic_id | Integer | Optional | Identifier of the direct messages topic to which the messages will be forwarded; required if the messages are forwarded to a direct messages chat |
| from_chat_id | Integer or String | Yes | Unique identifier for the chat where the original messages were sent (or username of the target bot, supergroup or channel in the format @username) |
| message_ids | Array of Integer | Yes | A JSON-serialized list of 1-100 identifiers of messages in the chat from_chat_id to forward. The identifiers must be specified in a strictly increasing order. |
| disable_notification | Boolean | Optional | Sends the messages silently. Users will receive a notification with no sound. |
| protect_content | Boolean | Optional | Protects the contents of the forwarded messages from forwarding and saving |

#### Example

```php

```

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 12.65. Full-Screen Message Effects

> Trigger full-screen celebration fireworks, flames, and hearts using message_effect_id.

#### The message_effect_id Parameter

   

Telegram Bot API 8.x introduced full-screen animation effects that cover the entire chat screen when a message arrives. Use the `message_effect_id` parameter in `sendMessage`.

   
    
| Effect ID | Animation Type | Best Used For |
| --- | --- | --- |
| 5046509860389126442 | 🎉 Celebration & Confetti | Welcome bonuses, payment completions, winning rewards. |
| 5104841245755180586 | 🔥 Burning Flames | Level ups, high streaks, hot broadcasts. |
| 5107584321108051014 | ❤️ Floating Hearts | Thank you messages, donations, gifts. |
| 5104858069142078847 | 👍 Thumbs Up Explosion | Approvals, confirmed orders, task completions. |

   

   
```php
function send_effect(string|int $chatId, string $text, string $effectId = '5046509860389126442'): array {
    return bot('sendMessage', [
        'chat_id'           => $chatId,
        'text'              => $text,
        'parse_mode'        => 'HTML',
        'message_effect_id' => $effectId
    ]);
}
```

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 12.66. getAvailableGifts

> Returns the list of gifts that can be sent by the bot to users and channel chats

Returns the list of gifts that can be sent by the bot to users and channel chats. Requires no parameters. Returns a Gifts object.

#### Example

```php

```

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 12.67. getBusinessAccountGifts

> Returns the gifts received and owned by a managed business account

Returns the gifts received and owned by a managed business account. Requires the *can_view_gifts_and_stars* business bot right. Returns OwnedGifts on success.

#### Parameters

| Parameter | Type | Required | Description |
| --- | --- | --- | --- |
| business_connection_id | String | Yes | Unique identifier of the business connection |
| exclude_unsaved | Boolean | Optional | Pass True to exclude gifts that aren't saved to the account's profile page |
| exclude_saved | Boolean | Optional | Pass True to exclude gifts that are saved to the account's profile page |
| exclude_unlimited | Boolean | Optional | Pass True to exclude gifts that can be purchased an unlimited number of times |
| exclude_limited_upgradable | Boolean | Optional | Pass True to exclude gifts that can be purchased a limited number of times and can be upgraded to unique |
| exclude_limited_non_upgradable | Boolean | Optional | Pass True to exclude gifts that can be purchased a limited number of times and can't be upgraded to unique |
| exclude_unique | Boolean | Optional | Pass True to exclude unique gifts |
| exclude_from_blockchain | Boolean | Optional | Pass True to exclude gifts that were assigned from the TON blockchain and can't be resold or transferred in Telegram |
| sort_by_price | Boolean | Optional | Pass True to sort results by gift price instead of send date. Sorting is applied before pagination. |
| offset | String | Optional | Offset of the first entry to return as received from the previous request; use empty string to get the first chunk of results |
| limit | Integer | Optional | The maximum number of gifts to be returned; 1-100. Defaults to 100. |

#### Example

```php

```

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 12.68. getBusinessAccountStarBalance

> Returns the amount of Telegram Stars owned by a managed business account

Returns the amount of Telegram Stars owned by a managed business account. Requires the *can_view_gifts_and_stars* business bot right. Returns StarAmount on success.

#### Parameters

| Parameter | Type | Required | Description |
| --- | --- | --- | --- |
| business_connection_id | String | Yes | Unique identifier of the business connection |

#### Example

```php

```

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 12.69. getBusinessConnection

> Use this method to get information about the connection of the bot with a business account

Use this method to get information about the connection of the bot with a business account. Returns a BusinessConnection object on success.

#### Parameters

| Parameter | Type | Required | Description |
| --- | --- | --- | --- |
| business_connection_id | String | Yes | Unique identifier of the business connection |

#### Example

```php

```

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 12.70. getChat

> Use this method to get up-to-date information about the chat

Use this method to get up-to-date information about the chat. Returns a ChatFullInfo object on success.

#### Parameters

| Parameter | Type | Required | Description |
| --- | --- | --- | --- |
| chat_id | Integer or String | Yes | Unique identifier for the target chat or username of the target supergroup or channel in the format @username |

#### Example

```php

```

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 12.71. getChatAdministrators

> Use this method to get a list of administrators in a chat

Use this method to get a list of administrators in a chat. Returns an Array of ChatMember objects.

#### Parameters

| Parameter | Type | Required | Description |
| --- | --- | --- | --- |
| chat_id | Integer or String | Yes | Unique identifier for the target chat or username of the target supergroup or channel in the format @username |
| return_bots | Boolean | Optional | Pass True to additionally receive all bots that are administrators of the chat. By default, bots other than the current bot are omitted. |

#### Example

```php

```

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 12.72. getChatGifts

> Returns the gifts owned by a chat

Returns the gifts owned by a chat. Returns OwnedGifts on success.

#### Parameters

| Parameter | Type | Required | Description |
| --- | --- | --- | --- |
| chat_id | Integer or String | Yes | Unique identifier for the target chat or username of the target channel in the format @username |
| exclude_unsaved | Boolean | Optional | Pass True to exclude gifts that aren't saved to the chat's profile page. Always True, unless the bot has the can_post_messages administrator right in the channel. |
| exclude_saved | Boolean | Optional | Pass True to exclude gifts that are saved to the chat's profile page. Always False, unless the bot has the can_post_messages administrator right in the channel. |
| exclude_unlimited | Boolean | Optional | Pass True to exclude gifts that can be purchased an unlimited number of times |
| exclude_limited_upgradable | Boolean | Optional | Pass True to exclude gifts that can be purchased a limited number of times and can be upgraded to unique |
| exclude_limited_non_upgradable | Boolean | Optional | Pass True to exclude gifts that can be purchased a limited number of times and can't be upgraded to unique |
| exclude_from_blockchain | Boolean | Optional | Pass True to exclude gifts that were assigned from the TON blockchain and can't be resold or transferred in Telegram |
| exclude_unique | Boolean | Optional | Pass True to exclude unique gifts |
| sort_by_price | Boolean | Optional | Pass True to sort results by gift price instead of send date. Sorting is applied before pagination. |
| offset | String | Optional | Offset of the first entry to return as received from the previous request; use an empty string to get the first chunk of results |
| limit | Integer | Optional | The maximum number of gifts to be returned; 1-100. Defaults to 100. |

#### Example

```php

```

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 12.73. getChatMember

> Use this method to get information about a member of a chat

**Botlify Native Shorthand:**

  `tg_is_member($channel, $userId);`

  Checks if user is a member/admin of a channel and returns true/false directly! See [Native Helpers Guide](?page=tg-native-helpers).
 

Use this method to get information about a member of a chat. The method is only guaranteed to work for other users if the bot is an administrator in the chat. Returns a ChatMember object on success.

#### Parameters

| Parameter | Type | Required | Description |
| --- | --- | --- | --- |
| chat_id | Integer or String | Yes | Unique identifier for the target chat or username of the target supergroup or channel in the format @username |
| user_id | Integer | Yes | Unique identifier of the target user |

#### Example

```php

```

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 12.74. getChatMemberCount

> Use this method to get the number of members in a chat

Use this method to get the number of members in a chat. Returns *Integer* on success.

#### Parameters

| Parameter | Type | Required | Description |
| --- | --- | --- | --- |
| chat_id | Integer or String | Yes | Unique identifier for the target chat or username of the target supergroup or channel in the format @username |

#### Example

```php

```

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 12.75. getChatMenuButton

> Use this method to get the current value of the bot's menu button in a private chat, or the default menu button

Use this method to get the current value of the bot's menu button in a private chat, or the default menu button. Returns MenuButton on success.

#### Parameters

| Parameter | Type | Required | Description |
| --- | --- | --- | --- |
| chat_id | Integer | Optional | Unique identifier for the target private chat. If not specified, the bot's default menu button will be returned. |

#### Example

```php

```

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 12.76. getCustomEmojiStickers

> Use this method to get information about custom emoji stickers by their identifiers

Use this method to get information about custom emoji stickers by their identifiers. Returns an Array of Sticker objects.

#### Parameters

| Parameter | Type | Required | Description |
| --- | --- | --- | --- |
| custom_emoji_ids | Array of String | Yes | A JSON-serialized list of custom emoji identifiers. At most 200 custom emoji identifiers can be specified. |

#### Example

```php

```

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 12.77. getFile

> Use this method to get basic information about a file and prepare it for downloading

Use this method to get basic information about a file and prepare it for downloading. For the moment, bots can download files of up to 20MB in size. On success, a File object is returned. The file can then be downloaded via the link `https://api.telegram.org/file/bot<token>/<file_path>`, where `<file_path>` is taken from the response. It is guaranteed that the link will be valid for at least 1 hour. When the link expires, a new one can be requested by calling getFile again.

**Note:** This function may not preserve the original file name and MIME type. You should save the file's MIME type and name (if available) when the File object is received.

#### Parameters

| Parameter | Type | Required | Description |
| --- | --- | --- | --- |
| file_id | String | Yes | File identifier to get information about |

#### Example

```php

```

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 12.78. getForumTopicIconStickers

> Use this method to get custom emoji stickers, which can be used as a forum topic icon by any user

Use this method to get custom emoji stickers, which can be used as a forum topic icon by any user. Requires no parameters. Returns an Array of Sticker objects.

#### Example

```php

```

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 12.79. getGameHighScores

> Use this method to get data for high score tables

Use this method to get data for high score tables. Will return the score of the specified user and several of their neighbors in a game. Returns an Array of GameHighScore objects.

This method will currently return scores for the target user, plus two of their closest neighbors on each side. Will also return the top three users if the user and their neighbors are not among them. Please note that this behavior is subject to change.

#### Parameters

| Parameter | Type | Required | Description |
| --- | --- | --- | --- |
| user_id | Integer | Yes | Target user id |
| chat_id | Integer | Optional | Required if inline_message_id is not specified. Unique identifier for the target chat. |
| message_id | Integer | Optional | Required if inline_message_id is not specified. Identifier of the sent message. |
| inline_message_id | String | Optional | Required if chat_id and message_id are not specified. Identifier of the inline message. |

#### Example

```php

```

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 12.80. getManagedBotAccessSettings

> Use this method to get the access settings of a managed bot

Use this method to get the access settings of a managed bot. Returns a BotAccessSettings object on success.

#### Parameters

| Parameter | Type | Required | Description |
| --- | --- | --- | --- |
| user_id | Integer | Yes | User identifier of the managed bot whose access settings will be returned |

#### Example

```php

```

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 12.81. getManagedBotToken

> Use this method to get the token of a managed bot

Use this method to get the token of a managed bot. Returns the token as *String* on success.

#### Parameters

| Parameter | Type | Required | Description |
| --- | --- | --- | --- |
| user_id | Integer | Yes | User identifier of the managed bot whose token will be returned |

#### Example

```php

```

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 12.82. getMe

> A simple method for testing your bot's authentication token

A simple method for testing your bot's authentication token. Requires no parameters. Returns basic information about the bot in form of a User object.

#### Example

```php

```

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 12.83. getMyCommands

> Use this method to get the current list of the bot's commands for the given scope and user language

Use this method to get the current list of the bot's commands for the given scope and user language. Returns an Array of BotCommand objects. If commands aren't set, an empty list is returned.

#### Parameters

| Parameter | Type | Required | Description |
| --- | --- | --- | --- |
| scope | BotCommandScope | Optional | A JSON-serialized object, describing scope of users. Defaults to BotCommandScopeDefault. |
| language_code | String | Optional | A two-letter ISO 639-1 language code or an empty string |

#### Example

```php

```

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 12.84. getMyDefaultAdministratorRights

> Use this method to get the current default administrator rights of the bot

Use this method to get the current default administrator rights of the bot. Returns ChatAdministratorRights on success.

#### Parameters

| Parameter | Type | Required | Description |
| --- | --- | --- | --- |
| for_channels | Boolean | Optional | Pass True to get default administrator rights of the bot in channels. Otherwise, default administrator rights of the bot for groups and supergroups will be returned. |

#### Example

```php

```

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 12.85. getMyDescription

> Use this method to get the current bot description for the given user language

Use this method to get the current bot description for the given user language. Returns BotDescription on success.

#### Parameters

| Parameter | Type | Required | Description |
| --- | --- | --- | --- |
| language_code | String | Optional | A two-letter ISO 639-1 language code or an empty string |

#### Example

```php

```

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 12.86. getMyName

> Use this method to get the current bot name for the given user language

Use this method to get the current bot name for the given user language. Returns BotName on success.

#### Parameters

| Parameter | Type | Required | Description |
| --- | --- | --- | --- |
| language_code | String | Optional | A two-letter ISO 639-1 language code or an empty string |

#### Example

```php

```

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 12.87. getMyShortDescription

> Use this method to get the current bot short description for the given user language

Use this method to get the current bot short description for the given user language. Returns BotShortDescription on success.

#### Parameters

| Parameter | Type | Required | Description |
| --- | --- | --- | --- |
| language_code | String | Optional | A two-letter ISO 639-1 language code or an empty string |

#### Example

```php

```

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 12.88. getMyStarBalance

> A method to get the current Telegram Stars balance of the bot

A method to get the current Telegram Stars balance of the bot. Requires no parameters. On success, returns a StarAmount object.

#### Example

```php

```

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 12.89. getStarTransactions

> Returns the bot's Telegram Star transactions in chronological order

Returns the bot's Telegram Star transactions in chronological order. On success, returns a StarTransactions object.

#### Parameters

| Parameter | Type | Required | Description |
| --- | --- | --- | --- |
| offset | Integer | Optional | Number of transactions to skip in the response |
| limit | Integer | Optional | The maximum number of transactions to be retrieved. Values between 1-100 are accepted. Defaults to 100. |

#### Example

```php

```

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 12.90. getStickerSet

> Use this method to get a sticker set

Use this method to get a sticker set. On success, a StickerSet object is returned.

#### Parameters

| Parameter | Type | Required | Description |
| --- | --- | --- | --- |
| name | String | Yes | Name of the sticker set |

#### Example

```php

```

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 12.91. getUpdates

> Use this method to receive incoming updates using long polling (wiki)

Use this method to receive incoming updates using long polling (wiki). Returns an Array of Update objects.

Please note that this parameter doesn't affect updates created before the call to getUpdates, so unwanted updates may be received for a short period of time.

**1.** This method will not work if an outgoing webhook is set up.

**2.** In order to avoid getting duplicate updates, recalculate *offset* after each server response.

#### Parameters

| Parameter | Type | Required | Description |
| --- | --- | --- | --- |
| offset | Integer | Optional | Identifier of the first update to be returned. Must be greater by one than the highest among the identifiers of previously received updates. By default, updates starting with the earliest unconfirmed update are returned. An update is considered confirmed as soon as getUpdates is called with an offset higher than its update_id. The negative offset can be specified to retrieve updates starting from -offset update from the end of the updates queue. All previous updates will be forgotten. |
| limit | Integer | Optional | Limits the number of updates to be retrieved. Values between 1-100 are accepted. Defaults to 100. |
| timeout | Integer | Optional | Timeout in seconds for long polling. Defaults to 0, i.e. usual short polling. Should be positive, short polling should be used for testing purposes only. |
| allowed_updates | Array of String | Optional | A JSON-serialized list of the update types you want your bot to receive. For example, specify ["message", "edited_channel_post", "callback_query"] to only receive updates of these types. See Update for a complete list of available update types. Specify an empty list to receive all update types except chat_member, message_reaction, and message_reaction_count (default). If not specified, the previous setting will be used. |

#### Example

```php

```

> [!NOTE]
> **Official Notes**
> Notes

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 12.92. getUserChatBoosts

> Use this method to get the list of boosts added to a chat by a user

Use this method to get the list of boosts added to a chat by a user. Requires administrator rights in the chat. Returns a UserChatBoosts object.

#### Parameters

| Parameter | Type | Required | Description |
| --- | --- | --- | --- |
| chat_id | Integer or String | Yes | Unique identifier for the chat or username of the channel in the format @username |
| user_id | Integer | Yes | Unique identifier of the target user |

#### Example

```php

```

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 12.93. getUserGifts

> Returns the gifts owned and hosted by a user

Returns the gifts owned and hosted by a user. Returns OwnedGifts on success.

#### Parameters

| Parameter | Type | Required | Description |
| --- | --- | --- | --- |
| user_id | Integer | Yes | Unique identifier of the user |
| exclude_unlimited | Boolean | Optional | Pass True to exclude gifts that can be purchased an unlimited number of times |
| exclude_limited_upgradable | Boolean | Optional | Pass True to exclude gifts that can be purchased a limited number of times and can be upgraded to unique |
| exclude_limited_non_upgradable | Boolean | Optional | Pass True to exclude gifts that can be purchased a limited number of times and can't be upgraded to unique |
| exclude_from_blockchain | Boolean | Optional | Pass True to exclude gifts that were assigned from the TON blockchain and can't be resold or transferred in Telegram |
| exclude_unique | Boolean | Optional | Pass True to exclude unique gifts |
| sort_by_price | Boolean | Optional | Pass True to sort results by gift price instead of send date. Sorting is applied before pagination. |
| offset | String | Optional | Offset of the first entry to return as received from the previous request; use an empty string to get the first chunk of results |
| limit | Integer | Optional | The maximum number of gifts to be returned; 1-100. Defaults to 100. |

#### Example

```php

```

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 12.94. getUserPersonalChatMessages

> Use this method to get the last messages from the personal chat (i.e., the chat currently added to their profile) of a given user

Use this method to get the last messages from the personal chat (i.e., the chat currently added to their profile) of a given user. On success, an Array of Message objects is returned.

#### Parameters

| Parameter | Type | Required | Description |
| --- | --- | --- | --- |
| user_id | Integer | Yes | Unique identifier for the target user |
| limit | Integer | Yes | The maximum number of messages to return; 1-20 |

#### Example

```php

```

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 12.95. getUserProfileAudios

> Use this method to get a list of profile audios for a user

Use this method to get a list of profile audios for a user. Returns a UserProfileAudios object.

#### Parameters

| Parameter | Type | Required | Description |
| --- | --- | --- | --- |
| user_id | Integer | Yes | Unique identifier of the target user |
| offset | Integer | Optional | Sequential number of the first audio to be returned. By default, all audios are returned. |
| limit | Integer | Optional | Limits the number of audios to be retrieved. Values between 1-100 are accepted. Defaults to 100. |

#### Example

```php

```

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 12.96. getUserProfilePhotos

> Use this method to get a list of profile pictures for a user

Use this method to get a list of profile pictures for a user. Returns a UserProfilePhotos object.

#### Parameters

| Parameter | Type | Required | Description |
| --- | --- | --- | --- |
| user_id | Integer | Yes | Unique identifier of the target user |
| offset | Integer | Optional | Sequential number of the first photo to be returned. By default, all photos are returned. |
| limit | Integer | Optional | Limits the number of photos to be retrieved. Values between 1-100 are accepted. Defaults to 100. |

#### Example

```php

```

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 12.97. getWebhookInfo

> Use this method to get current webhook status

Use this method to get current webhook status. Requires no parameters. On success, returns a WebhookInfo object. If the bot is using getUpdates, will return an object with the *url* field empty.

#### Example

```php

```

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 12.98. giftPremiumSubscription

> Gifts a Telegram Premium subscription to the given user

Gifts a Telegram Premium subscription to the given user. Returns *True* on success.

#### Parameters

| Parameter | Type | Required | Description |
| --- | --- | --- | --- |
| user_id | Integer | Yes | Unique identifier of the target user who will receive a Telegram Premium subscription |
| month_count | Integer | Yes | Number of months the Telegram Premium subscription will be active for the user; must be one of 3, 6, or 12 |
| star_count | Integer | Yes | Number of Telegram Stars to pay for the Telegram Premium subscription; must be 1000 for 3 months, 1500 for 6 months, and 2500 for 12 months |
| text | String | Optional | Text that will be shown along with the service message about the subscription; 0-128 characters |
| text_parse_mode | String | Optional | Mode for parsing entities in the text. See formatting options for more details. Entities other than "bold", "italic", "underline", "strikethrough", "spoiler", "custom_emoji", and "date_time" are ignored. |
| text_entities | Array of MessageEntity | Optional | A JSON-serialized list of special entities that appear in the gift text. It can be specified instead of text_parse_mode. Entities other than "bold", "italic", "underline", "strikethrough", "spoiler", "custom_emoji", and "date_time" are ignored. |

#### Example

```php

```

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 12.99. Group & Channel Management, Permissions & Bans

> Comprehensive guide to banChatMember, restrictChatMember (mute/permissions), promoteChatMember, admin custom titles, and invite links.

#### Supergroup & Channel Administration

   

Telegram bots with administrative privileges can autonomously police communities, enforce rate limits, mute spammers, promote trusted moderators, and generate trackable invite links.

   

#### 1. Banning & Unbanning Members (banChatMember)

   

Banning removes a user from the supergroup/channel and prevents them from rejoining:

   
```php

```

   

#### 2. Muting Users & Granular ChatPermissions (restrictChatMember)

   

Rather than kicking users, you can restrict specific actions (e.g. forbid sending media, links, or text) using the `ChatPermissions` object:

   
```php

```

   

#### 3. Promoting Administrators & Setting Custom Titles

   

Assign specific administrative rights and custom badge titles (e.g. "👑 Senior Mod") to group members:

   
```php

```

   

#### 4. Creating & Managing Trackable Chat Invite Links

   

Generate unique invite links with expiration dates, member quotas, or mandatory admin approval:

   
```php

```

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 12.100. hideGeneralForumTopic

> Use this method to hide the 'General' topic in a forum supergroup chat

Use this method to hide the 'General' topic in a forum supergroup chat. The bot must be an administrator in the chat for this to work and must have the *can_manage_topics* administrator rights. The topic will be automatically closed if it was open. Returns *True* on success.

#### Parameters

| Parameter | Type | Required | Description |
| --- | --- | --- | --- |
| chat_id | Integer or String | Yes | Unique identifier for the target chat or username of the target supergroup in the format @username |

#### Example

```php

```

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 12.101. In-Telegram Admin Suite (/admin) & User Management

> Native Telegram-based administrative control center with telemetry, user search, custom ban reasons, and hierarchical navigation.

#### The Native In-Telegram Admin Suite

   

Every professional Telegram bot requires a powerful administrative dashboard accessible directly inside Telegram without logging into an external web portal. Botlify Cloud establishes a standardized architectural pattern for building secure, intuitive in-bot admin panels.

   

#### 1. Strict Security Gate

   

The admin suite is gated strictly by `ADMIN_CHAT_ID` (provisioned automatically via environment variables). If any unauthorized user attempts to send `/admin` or trigger admin callback queries, the bot must silently terminate execution with zero response and zero data exposure:

      
```php

```

   

#### 2. Hierarchical Back Navigation (admin_home)

   

To maintain seamless UX, administrative sub-sections (such as Statistics, User Management, Broadcast, or Tickets) must never redirect the administrator back to the general user menu. All admin sub-menu `« Back` buttons must specify `callback_data => 'admin_home'`, editing the existing message in-place back to the main admin control center. An explicit `« Exit to Bot Menu` button (`admin_exit`) is provided for intentional exits.

   

#### 3. Real-Time Bot Telemetry & Analytics (admin_stats)

   

The analytics view displays live bot statistics queried directly from the local SQLite database:

   
    
- Total Registered Users & Today's Active Users (24h).

    
- Currently Suspended / Banned Users count.

    
- Domain-specific metrics (e.g., Total Revenue, Open Support Tickets, Total Orders, Paid Referrals).

    
- Server Engine status (SQLite WAL Mode, PHP version).

   

   

#### 4. User Management, Dossier Inspection & Ban Firewall

   

Administrators can search any user by numeric Chat ID or `@username` using a dedicated FSM search prompt. The bot renders a detailed user dossier:

   
    
- **Account Info:** User ID, Username, Display Name, Registration Date, Total Transactions.

    
- **Interactive Action Buttons:**
     
      `[🔴 Ban User]` — Prompts admin for a mandatory **Ban Reason**, updates the database with `is_banned = 1` and `ban_reason`, and blocks the user.

      
- `[🟢 Unban User]` — Restores user access and clears the ban flag.

     
    
   

   
> [!WARNING]
> **Instant Ban Firewall & Keyboard Removal**
> When a banned user attempts to interact with the bot, the ban firewall intercepts the request, displays the custom suspension reason, executes reply_markup => ['remove_keyboard' => true] to strip all menu buttons from their screen, and halts execution immediately.

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 12.102. Interactive Polls & Quizzes (sendPoll & poll_answer)

> Create regular voting polls, educational trivia quizzes with explanations, timer deadlines, and process live voting updates.

#### Interactive Polls & Trivia Quizzes Overview

   

Telegram polls allow bots to engage communities, run democratic elections, or administer educational quizzes with instant correct/wrong animations and confetti. Poll updates arrive via the `poll_answer` webhook object.

   

#### 1. Creating Regular Polls vs. Quiz Mode

   
    
| Poll Type | Key Parameters | Behavior in Telegram |
| --- | --- | --- |
| Regular Poll | type => 'regular', allows_multiple_answers, is_anonymous | Standard public or anonymous voting. Users can retract or change their vote unless poll is closed. |
| Quiz Mode | type => 'quiz', correct_option_id, explanation | Users choose once. Correct answer triggers celebratory confetti; wrong answer displays the explanation tooltip. |

   

   
```php

```

   

#### 2. Stopping / Closing a Poll Programmatically

   

When a contest ends or voting deadline arrives, freeze the poll using `stopPoll`:

   
```php

```

   

#### 3. Handling Live poll_answer Webhook Updates

   

When a user casts or changes a vote in a non-anonymous poll, Telegram dispatches a `poll_answer` update to your webhook:

   
```php

```

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 12.103. Keyboards, Button Styles, Mini Apps & Reply Controls

> Telegram 8.0 button styles (primary, success, danger), custom emoji icons, inline buttons, hardware data pickers, and reply controls.

#### Inline Keyboards vs. Reply Keyboards

   

Telegram supports two distinct interactive interface paradigms:

   
    
- **Inline Keyboards (`InlineKeyboardMarkup`):** Attached directly underneath specific message bubbles. Tapping a button triggers a background `callback_query`, opens an external URL, launches a full-screen Telegram Mini App, copies text to clipboard, or executes seamless OAuth authentication.

    
- **Reply Keyboards (`ReplyKeyboardMarkup`):** Replace the user's on-screen virtual keyboard with fixed or persistent command tiles, contact/GPS hardware requests, or native user/chat pickers.

   

   
> [!TIP]
> **Telegram 8.0 Button Colors (style parameter)**
> In Telegram Bot API 8.0+, both InlineKeyboardButton and KeyboardButton support the style parameter:
>      
>       "primary" — Dark Blue color for highlighted actions and primary calls-to-action.
>       "success" — Emerald Green color for approvals, confirmations, and successful purchases.
>       "danger" — Crimson Red color for destructive actions, deletions, bans, and cancellations.

   

#### 1. Complete Telegram 8.0 Styled Inline Keyboard Example

   

Demonstrating colored buttons (`primary`, `success`, `danger`), custom emoji prefixes (`icon_custom_emoji_id`), and one-tap clipboard copy:

   
```php

```

   
> [!WARNING]
> **Always Answer Callback Queries Promptly!**
> Whenever a user taps an inline callback button, Telegram displays a spinning loader on the button. You must immediately call bot('answerCallbackQuery', ['callback_query_id' => $cbId]) to dismiss the spinner and provide optional haptic/toast notifications.

   

#### 2. The 9 Inline Button Types Matrix

   
    
| Button Type | Key Payload Property | Behavior & Capabilities |
| --- | --- | --- |
| Callback Button | callback_data => 'act_1' | Dispatches background webhook update (1 to 64 bytes). Supports style and icon_custom_emoji_id. |
| URL Button | url => 'https://...' | Opens external web link in user's browser or in-app browser. |
| Mini App Button | web_app => ['url' => '...'] | Launches Telegram Web App directly inside the messenger with full JavaScript bridge. |
| Copy Text Button | copy_text => ['text' => '...'] | Copies specified string directly into device clipboard with single tap (API 7.10+). |
| Switch Inline Query | switch_inline_query => 'query' | Prompts user to select a chat and enters bot's inline query. |
| Switch Chosen Chat | switch_inline_query_chosen_chat | Filters destination chats (e.g. channel-only, group-only, user-only) before forwarding query. |
| Telegram Web OAuth | login_url => ['url' => '...'] | One-tap seamless web login passing verified Telegram auth token to your website. |
| Invoice Pay Button | pay => true | Must be the first button in the first row of an invoice message to trigger payment sheet. |
| HTML5 Game Button | callback_game => [] | Launches interactive canvas/HTML5 game configured via @BotFather. |

   

   
```php

```

   

#### 3. Reply Keyboards with Button Styles & Data Pickers

   

Reply keyboards also support modern button styles (`primary`, `danger`, `success`), hardware data sharing, and native Telegram pickers for selecting specific users or channels:

   
```php

```

   

#### 4. Keyboard Dismissal & Force Reply Controls

   
```php

```

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 12.104. leaveChat

> Use this method for your bot to leave a group, supergroup or channel

Use this method for your bot to leave a group, supergroup or channel. Returns *True* on success.

#### Parameters

| Parameter | Type | Required | Description |
| --- | --- | --- | --- |
| chat_id | Integer or String | Yes | Unique identifier for the target chat or username of the target supergroup or channel in the format @username. Channel direct messages chats aren't supported; leave the corresponding channel instead. |

#### Example

```php

```

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 12.105. logOut

> Use this method to log out from the cloud Bot API server before launching the bot locally

Use this method to log out from the cloud Bot API server before launching the bot locally. You **must** log out the bot before running it locally, otherwise there is no guarantee that the bot will receive updates. After a successful call, you can immediately log in on a local server, but will not be able to log in back to the cloud Bot API server for 10 minutes. Returns *True* on success. Requires no parameters.

#### Example

```php

```

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 12.106. Mandatory Force-Subscribe System

> Protect bot features by requiring users to join your official Telegram channel or group before proceeding.

#### How Force-Subscribe Works

   
    
- Add your bot as an **Administrator** in your official channel or group.

    
- When a user sends `/start`, call `getChatMember` with your channel ID and the user's ID.

    
- Inspect the returned `status`. If status is `left` or `kicked`, block access and present a Join Channel button with a *"Check Membership"* callback.

   

   
```php
function is_subscribed(string|int $userId, string|int $channelId): bool {
    $res = bot('getChatMember', [
        'chat_id' => $channelId,
        'user_id' => $userId
    ]);
    if (empty($res['ok'])) return false;
    $status = $res['result']['status'] ?? '';
    return in_array($status, ['creator', 'administrator', 'member', 'restricted'], true);
}

// In your webhook handler:
define('REQUIRED_CHANNEL', '@BotlifyOfficial');

if (!is_subscribed($chatId, REQUIRED_CHANNEL)) {
    bot('sendMessage', [
        'chat_id'    => $chatId,
        'text'       => "⚠️ Access Restricted!

You must join our official channel to use this bot.",
        'parse_mode' => 'HTML',
        'reply_markup' => [
            'inline_keyboard' => [
                [['text' => '📢 Join Channel', 'url' => 'https://t.me/BotlifyOfficial']],
                [['text' => '🔄 Verify Membership', 'callback_data' => 'check_sub']]
            ]
        ]
    ]);
    exit('ok');
}
```

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 12.107. Media, Audio, Voice, Video Notes, Stickers & Games

> Send photos, videos with covers and start timestamps, audio, voice messages, round video notes, sticker sets, and Telegram HTML5 games.

#### Telegram Media API Overview

   

Telegram allows bots to dispatch rich multimedia assets via direct public URLs, cached Telegram `file_id` strings, or multipart form uploads. All media methods support HTML captions with inline spoilers.

   
    
| Method | Media Type | Key Parameters |
| --- | --- | --- |
| sendPhoto | JPG, PNG, WebP image | photo, caption, has_spoiler |
| sendVideo | MP4, H.264 video | video, cover, start_timestamp, supports_streaming |
| sendAudio | MP3, M4A music track | audio, performer, title, duration, thumbnail |
| sendVoice | OGG Opus voice memo | voice, duration, caption |
| sendVideoNote | Circular video clip (1:1 ratio) | video_note, length, duration, thumbnail |
| sendDocument | PDF, ZIP, APK, generic file | document, caption, thumbnail |
| sendAnimation | GIF or soundless MP4 animation | animation, caption, has_spoiler |
| sendMediaGroup | Album of 2 to 10 photos/videos | media (JSON-encoded array of InputMedia) |
| sendSticker | WebP, TGS animated, or WebM video | sticker, emoji |
| sendGame | Telegram HTML5 Web Game | game_short_name, reply_markup |

   

   

#### 1. Sending Photos, Videos with Custom Covers & Timestamps

   

In API 8.x, `sendVideo` supports custom thumbnail covers and jumping to a specific playback second:

   
```php

```

   

#### 2. Sending Voice Memos & Round Video Notes

   

Voice messages (OGG Opus) render as audio wavebars with 1.5x/2x playback controls. Video notes render as circular clips:

   
```php

```

   

#### 3. Sending Media Groups (Albums of up to 10 Items)

   

Combine multiple photos and videos into a single contiguous grid layout:

   
```php

```

   

#### 4. Stickers & Telegram HTML5 Games

   
```php

```

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 12.108. Messages, Editing, Pinning & Rich Text Formatting

> Complete guide to sendMessage, editMessageText, deleteMessage, pinChatMessage, copyMessage, and full HTML / MarkdownV2 rich typography.

#### Telegram Message Lifecycle Overview

   

Every interaction in Telegram begins with message delivery. Beyond standard text, Telegram bots have complete programmatic control over editing existing bubbles, deleting spam, pinning announcements, forwarding/copying messages, and styling typography with rich HTML and MarkdownV2 entities.

   

#### 1. Sending Messages & Link Preview Options (sendMessage)

   

In modern Telegram Bot API (v7.0+ / 8.x), link previews are controlled via the dedicated `link_preview_options` object rather than deprecated boolean flags:

   
```php

```

   

#### 2. Comprehensive HTML Formatting Reference

   

Botlify Cloud strongly recommends `parse_mode => 'HTML'` for all bot messages because HTML tags can be safely escaped with PHP's native `htmlspecialchars($var, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8')` without risk of syntax breaks.

   
    
| Formatting Style | HTML Tag Syntax | Visual Output / Behavior |
| --- | --- | --- |
| Bold | bold text or text | bold text |
| Italic | italic text or text | italic text |
| Underline | underlined text or text | underlined text |
| Strikethrough | strikethrough or text | strikethrough |
| Spoiler | secret | Blurs text until user taps to reveal |
| Inline Code | $balance = 50; | Monospaced inline snippet (one-tap copy in Telegram) |
| Code Block | code | Multi-line monospaced block with syntax label |
| Blockquote | Quoted note | Indented quotation with accent bar |
| Expandable Quote | Long text... | Collapsible quotation with "Show More" accordion (API 7.3+) |
| Hyperlink | Visit Site | Clickable web link |
| Mention by User ID | John Doe | Mentions user even if they do not have a public username |
| Custom Emoji | 🔥 | Renders verified Telegram Premium custom emoji (API 6.2+) |

   

   
```php

```

   

#### 3. Editing Messages & Captions Dynamically

   

Rather than sending a flood of new messages, update existing bubbles in place to create smooth, app-like interfaces:

   
```php

```

   

#### 4. Deleting, Pinning & Copying Messages

   
```php

```

   

#### 5. Realistic Bot UX with Chat Actions (sendChatAction)

   

When performing heavy tasks (such as AI generation, downloading files, or complex SQLite queries), tell the user your bot is working by showing dynamic status indicators in the Telegram header:

   
    
| Action Name | Displayed Header Status | Ideal Use Case |
| --- | --- | --- |
| typing | "is typing..." | Waiting for AI responses, text formatting, or database lookups. |
| upload_photo | "is sending a photo..." | Generating or fetching high-resolution images. |
| record_video / upload_video | "is sending a video..." | Processing or uploading MP4 video files. |
| record_voice / upload_voice | "is sending audio..." | Synthesizing text-to-speech voice memos. |
| upload_document | "is sending a file..." | Compiling ZIP archives or generating PDF reports. |
| choose_sticker | "is choosing a sticker..." | Selecting animated or reaction stickers. |
| record_video_note | "is sending a video message..." | Processing circular round video notes. |

   

   
```php

```

   

#### 6. Real-Time Streaming Message Drafts (sendMessageDraft)

   

Telegram allows AI bots to stream partial message drafts in real time to the user while content is being generated:

   
```php

```

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 12.109. Payments, Telegram Stars & Digital Goods

> Accept Telegram Stars (⭐️) for digital goods, handle recurring monthly subscriptions, answer pre_checkout_query, and issue refunds.

#### The Telegram Stars Ecosystem (⭐️)

   

**Telegram Stars (⭐️)** are Telegram's native virtual currency used to pay for digital goods, downloads, premium services, and recurring subscriptions inside bots. Telegram handles App Store and Google Play compliance, credit card processing, and chargeback security.

   
> [!TIP]
> **Currency Code: XTR**
> For all Telegram Stars payments, the currency parameter must strictly be set to 'XTR'.

   

#### 1. Creating Stars Invoices (One-Time & Recurring Subscriptions)

   

You can send an invoice card directly into chat using `sendInvoice`, or generate a shareable checkout URL via `createInvoiceLink`:

   
```php

```

   

#### 2. Handling the Two-Step Payment Webhook Lifecycle

   

Telegram Stars payments execute in two distinct webhook phases:

   
    
- **`pre_checkout_query`:** Sent right when the user taps "Pay ⭐️". Your bot has **10 seconds** to confirm order validity. You MUST respond with `answerPreCheckoutQuery(['pre_checkout_query_id' => $id, 'ok' => true])`.

    
- **`successful_payment`:** Sent inside a standard message update once Telegram successfully debits the Stars. You deliver the product and record the transaction in `database.db`.

   

   
```php

```

   

#### 3. Refunding Stars Payments & Inspecting Ledger

   

If a customer requests a refund or disputes a transaction, you can refund their Stars directly using `refundStarPayment`:

   
```php

```

   

#### 4. Telegram Stars Paid Gifts API (sendGift & getAvailableGifts)

   

Telegram allows bots to send digital gifts powered by Telegram Stars directly to users or channel chats:

   
```php

```

   

#### 5. Affiliate Programs & Referral Commissions (AffiliateInfo)

   

Bots with affiliate programs can reward promoters who refer customers. In Telegram Bot API 8.0+, transactions include the `affiliate` field inside `TransactionPartnerUser` detailing commission percentages and promoter User IDs.

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 12.110. pinChatMessage

> Use this method to add a message to the list of pinned messages in a chat

Use this method to add a message to the list of pinned messages in a chat. In private chats and channel direct messages chats, all non-service messages can be pinned. Conversely, the bot must be an administrator with the 'can_pin_messages' right or the 'can_edit_messages' right to pin messages in groups and channels respectively. Returns *True* on success.

#### Parameters

| Parameter | Type | Required | Description |
| --- | --- | --- | --- |
| business_connection_id | String | Optional | Unique identifier of the business connection on behalf of which the message will be pinned |
| chat_id | Integer or String | Yes | Unique identifier for the target chat or username of the target channel in the format @username |
| message_id | Integer | Yes | Identifier of a message to pin |
| disable_notification | Boolean | Optional | Pass True if it is not necessary to send a notification to all chat members about the new pinned message. Notifications are always disabled in channels and private chats. |

#### Example

```php

```

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 12.111. postStory

> Posts a story on behalf of a managed business account

Posts a story on behalf of a managed business account. Requires the *can_manage_stories* business bot right. Returns Story on success.

#### Parameters

| Parameter | Type | Required | Description |
| --- | --- | --- | --- |
| business_connection_id | String | Yes | Unique identifier of the business connection |
| content | InputStoryContent | Yes | Content of the story |
| active_period | Integer | Yes | Period after which the story is moved to the archive, in seconds; must be one of 6  3600, 12  3600, 86400, or 2 * 86400 |
| caption | String | Optional | Caption of the story, 0-2048 characters after entities parsing |
| parse_mode | String | Optional | Mode for parsing entities in the story caption. See formatting options for more details. |
| caption_entities | Array of MessageEntity | Optional | A JSON-serialized list of special entities that appear in the caption, which can be specified instead of parse_mode |
| areas | Array of StoryArea | Optional | A JSON-serialized list of clickable areas to be shown on the story |
| post_to_chat_page | Boolean | Optional | Pass True to keep the story accessible after it expires |
| protect_content | Boolean | Optional | Pass True if the content of the story must be protected from forwarding and screenshotting |

#### Example

```php

```

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 12.112. promoteChatMember

> Use this method to promote or demote a user in a supergroup or a channel

Use this method to promote or demote a user in a supergroup or a channel. The bot must be an administrator in the chat for this to work and must have the appropriate administrator rights. Pass *False* for all boolean parameters to demote a user. Returns *True* on success.

#### Parameters

| Parameter | Type | Required | Description |
| --- | --- | --- | --- |
| chat_id | Integer or String | Yes | Unique identifier for the target chat or username of the target channel in the format @username |
| user_id | Integer | Yes | Unique identifier of the target user |
| is_anonymous | Boolean | Optional | Pass True if the administrator's presence in the chat is hidden |
| can_manage_chat | Boolean | Optional | Pass True if the administrator can access the chat event log, get boost list, see hidden supergroup and channel members, report spam messages, ignore slow mode, and send messages to the chat without paying Telegram Stars. Implied by any other administrator privilege. |
| can_delete_messages | Boolean | Optional | Pass True if the administrator can delete messages of other users |
| can_manage_video_chats | Boolean | Optional | Pass True if the administrator can manage video chats |
| can_restrict_members | Boolean | Optional | Pass True if the administrator can restrict, ban or unban chat members, or access supergroup statistics. For backward compatibility, defaults to True for promotions of channel administrators. |
| can_promote_members | Boolean | Optional | Pass True if the administrator can add new administrators with a subset of their own privileges or demote administrators that they have promoted, directly or indirectly (promoted by administrators that were appointed by him) |
| can_change_info | Boolean | Optional | Pass True if the administrator can change chat title, photo and other settings |
| can_invite_users | Boolean | Optional | Pass True if the administrator can invite new users to the chat |
| can_post_stories | Boolean | Optional | Pass True if the administrator can post stories to the chat |
| can_edit_stories | Boolean | Optional | Pass True if the administrator can edit stories posted by other users, post stories to the chat page, pin chat stories, and access the chat's story archive |
| can_delete_stories | Boolean | Optional | Pass True if the administrator can delete stories posted by other users |
| can_post_messages | Boolean | Optional | Pass True if the administrator can post messages in the channel, approve suggested posts, or access channel statistics; for channels only |
| can_edit_messages | Boolean | Optional | Pass True if the administrator can edit messages of other users and can pin messages; for channels only |
| can_pin_messages | Boolean | Optional | Pass True if the administrator can pin messages; for supergroups only |
| can_manage_topics | Boolean | Optional | Pass True if the user is allowed to create, rename, close, and reopen forum topics; for supergroups only |
| can_manage_direct_messages | Boolean | Optional | Pass True if the administrator can manage direct messages within the channel and decline suggested posts; for channels only |
| can_manage_tags | Boolean | Optional | Pass True if the administrator can edit the tags of regular members; for groups and supergroups only |
| can_send_welcome_messages | Boolean | Optional | Pass True if the administrator can manage chat welcome messages or directly send them in the case of bots |

#### Example

```php

```

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 12.113. readBusinessMessage

> Marks incoming message as read on behalf of a business account

Marks incoming message as read on behalf of a business account. Requires the *can_read_messages* business bot right. Returns *True* on success.

#### Parameters

| Parameter | Type | Required | Description |
| --- | --- | --- | --- |
| business_connection_id | String | Yes | Unique identifier of the business connection on behalf of which to read the message |
| chat_id | Integer | Yes | Unique identifier of the chat in which the message was received. The chat must have been active in the last 24 hours. |
| message_id | Integer | Yes | Unique identifier of the message to mark as read |

#### Example

```php

```

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 12.114. refundStarPayment

> Refunds a successful payment in Telegram Stars

Refunds a successful payment in Telegram Stars. Returns *True* on success.

#### Parameters

| Parameter | Type | Required | Description |
| --- | --- | --- | --- |
| user_id | Integer | Yes | Identifier of the user whose payment will be refunded |
| telegram_payment_charge_id | String | Yes | Telegram payment identifier |

#### Example

```php

```

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 12.115. removeBusinessAccountProfilePhoto

> Removes the current profile photo of a managed business account

Removes the current profile photo of a managed business account. Requires the *can_edit_profile_photo* business bot right. Returns *True* on success.

#### Parameters

| Parameter | Type | Required | Description |
| --- | --- | --- | --- |
| business_connection_id | String | Yes | Unique identifier of the business connection |
| is_public | Boolean | Optional | Pass True to remove the public photo, which is visible even if the main photo is hidden by the business account's privacy settings. After the main photo is removed, the previous profile photo (if present) becomes the main photo. |

#### Example

```php

```

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 12.116. removeChatVerification

> Removes verification from a chat that is currently verified on behalf of the organization represented by the bot

Removes verification from a chat that is currently verified on behalf of the organization represented by the bot. Returns *True* on success.

#### Parameters

| Parameter | Type | Required | Description |
| --- | --- | --- | --- |
| chat_id | Integer or String | Yes | Unique identifier for the target chat or username of the target bot or channel in the format @username |

#### Example

```php

```

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 12.117. removeMyProfilePhoto

> Removes the profile photo of the bot

Removes the profile photo of the bot. Requires no parameters. Returns *True* on success.

#### Example

```php

```

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 12.118. removeUserVerification

> Removes verification from a user who is currently verified on behalf of the organization represented by the bot

Removes verification from a user who is currently verified on behalf of the organization represented by the bot. Returns *True* on success.

#### Parameters

| Parameter | Type | Required | Description |
| --- | --- | --- | --- |
| user_id | Integer | Yes | Unique identifier of the target user |

#### Example

```php

```

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 12.119. reopenForumTopic

> Use this method to reopen a closed topic in a forum supergroup chat

Use this method to reopen a closed topic in a forum supergroup chat. The bot must be an administrator in the chat for this to work and must have the *can_manage_topics* administrator rights, unless it is the creator of the topic. Returns *True* on success.

#### Parameters

| Parameter | Type | Required | Description |
| --- | --- | --- | --- |
| chat_id | Integer or String | Yes | Unique identifier for the target chat or username of the target supergroup in the format @username |
| message_thread_id | Integer | Yes | Unique identifier for the target message thread of the forum topic |

#### Example

```php

```

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 12.120. reopenGeneralForumTopic

> Use this method to reopen a closed 'General' topic in a forum supergroup chat

Use this method to reopen a closed 'General' topic in a forum supergroup chat. The bot must be an administrator in the chat for this to work and must have the *can_manage_topics* administrator rights. The topic will be automatically unhidden if it was hidden. Returns *True* on success.

#### Parameters

| Parameter | Type | Required | Description |
| --- | --- | --- | --- |
| chat_id | Integer or String | Yes | Unique identifier for the target chat or username of the target supergroup in the format @username |

#### Example

```php

```

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 12.121. replaceManagedBotToken

> Use this method to revoke the current token of a managed bot and generate a new one

Use this method to revoke the current token of a managed bot and generate a new one. Returns the new token as *String* on success.

#### Parameters

| Parameter | Type | Required | Description |
| --- | --- | --- | --- |
| user_id | Integer | Yes | User identifier of the managed bot whose token will be replaced |

#### Example

```php

```

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 12.122. replaceStickerInSet

> Use this method to replace an existing sticker in a sticker set with a new one

Use this method to replace an existing sticker in a sticker set with a new one. The method is equivalent to calling deleteStickerFromSet, then addStickerToSet, then setStickerPositionInSet. Returns *True* on success.

#### Parameters

| Parameter | Type | Required | Description |
| --- | --- | --- | --- |
| user_id | Integer | Yes | User identifier of the sticker set owner |
| name | String | Yes | Sticker set name |
| old_sticker | String | Yes | File identifier of the replaced sticker |
| sticker | InputSticker | Yes | A JSON-serialized object with information about the added sticker. If exactly the same sticker had already been added to the set, then the set remains unchanged. |

#### Example

```php

```

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 12.123. repostStory

> Reposts a story on behalf of a business account from another business account

Reposts a story on behalf of a business account from another business account. Both business accounts must be managed by the same bot, and the story on the source account must have been posted (or reposted) by the bot. Requires the *can_manage_stories* business bot right for both business accounts. Returns Story on success.

#### Parameters

| Parameter | Type | Required | Description |
| --- | --- | --- | --- |
| business_connection_id | String | Yes | Unique identifier of the business connection |
| from_chat_id | Integer | Yes | Unique identifier of the chat which posted the story that should be reposted |
| from_story_id | Integer | Yes | Unique identifier of the story that should be reposted |
| active_period | Integer | Yes | Period after which the story is moved to the archive, in seconds; must be one of 6  3600, 12  3600, 86400, or 2 * 86400 |
| post_to_chat_page | Boolean | Optional | Pass True to keep the story accessible after it expires |
| protect_content | Boolean | Optional | Pass True if the content of the story must be protected from forwarding and screenshotting |

#### Example

```php

```

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 12.124. restrictChatMember

> Use this method to restrict a user in a supergroup

Use this method to restrict a user in a supergroup. The bot must be an administrator in the supergroup for this to work and must have the appropriate administrator rights. Pass *True* for all permissions to lift restrictions from a user. Returns *True* on success.

#### Parameters

| Parameter | Type | Required | Description |
| --- | --- | --- | --- |
| chat_id | Integer or String | Yes | Unique identifier for the target chat or username of the target supergroup in the format @username |
| user_id | Integer | Yes | Unique identifier of the target user |
| permissions | ChatPermissions | Yes | A JSON-serialized object for new user permissions |
| use_independent_chat_permissions | Boolean | Optional | Pass True if chat permissions are set independently. Otherwise, the can_send_other_messages and can_add_web_page_previews permissions will imply the can_send_messages, can_send_audios, can_send_documents, can_send_photos, can_send_videos, can_send_video_notes, and can_send_voice_notes permissions; the can_send_polls permission will imply the can_send_messages permission. |
| until_date | Integer | Optional | Date when restrictions will be lifted for the user; Unix time. If user is restricted for more than 366 days or less than 30 seconds from the current time, they are considered to be restricted forever. |

#### Example

```php

```

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 12.125. revokeChatInviteLink

> Use this method to revoke an invite link created by the bot

Use this method to revoke an invite link created by the bot. If the primary link is revoked, a new link is automatically generated. The bot must be an administrator in the chat for this to work and must have the appropriate administrator rights. Returns the revoked invite link as ChatInviteLink object.

#### Parameters

| Parameter | Type | Required | Description |
| --- | --- | --- | --- |
| chat_id | Integer or String | Yes | Unique identifier of the target chat or username of the target channel in the format @username |
| invite_link | String | Yes | The invite link to revoke |

#### Example

```php

```

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 12.126. savePreparedInlineMessage

> Stores a message that can be sent by a user of a Mini App

Stores a message that can be sent by a user of a Mini App. Returns a PreparedInlineMessage object.

#### Parameters

| Parameter | Type | Required | Description |
| --- | --- | --- | --- |
| user_id | Integer | Yes | Unique identifier of the target user that can use the prepared message |
| result | InlineQueryResult | Yes | A JSON-serialized object describing the message to be sent |
| allow_user_chats | Boolean | Optional | Pass True if the message can be sent to private chats with users |
| allow_bot_chats | Boolean | Optional | Pass True if the message can be sent to private chats with bots |
| allow_group_chats | Boolean | Optional | Pass True if the message can be sent to group and supergroup chats |
| allow_channel_chats | Boolean | Optional | Pass True if the message can be sent to channel chats |

#### Example

```php

```

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 12.127. savePreparedKeyboardButton

> Stores a keyboard button that can be used by a user within a Mini App

Stores a keyboard button that can be used by a user within a Mini App. Returns a PreparedKeyboardButton object.

#### Parameters

| Parameter | Type | Required | Description |
| --- | --- | --- | --- |
| user_id | Integer | Yes | Unique identifier of the target user that can use the button |
| button | KeyboardButton | Yes | A JSON-serialized object describing the button to be saved. The button must be of the type request_users, request_chat, or request_managed_bot. |

#### Example

```php

```

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 12.128. Seamless Telegram Web OAuth Login

> Authenticate Telegram users onto web applications seamlessly with one tap using login_url.

#### The login_url Parameter

   

Instead of requiring users to enter passwords or 2FA codes on your website, you can attach a `login_url` button in Telegram chat. When clicked, Telegram securely prompts the user and passes verified user data via GET parameters to your auth endpoint.

   
```php
bot('sendMessage', [
    'chat_id'      => $chatId,
    'text'         => "🔐 Access Your Web Dashboard:
Click below to log in securely without entering credentials.",
    'parse_mode'   => 'HTML',
    'reply_markup' => [
        'inline_keyboard' => [
            [
                [
                    'text'      => '🚀 One-Click Web Login',
                    'login_url' => [
                        'url'                => 'https://botlify.cloud/login.php?telegram_oauth=1',
                        'forward_text'       => 'Log in to Botlify Cloud',
                        'request_write_access' => true
                    ]
                ]
            ]
        ]
    ]
]);
```

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 12.129. sendAnimation

> Use this method to send animation files (GIF or H.264/MPEG-4 AVC video without sound)

Use this method to send animation files (GIF or H.264/MPEG-4 AVC video without sound). On success, the sent Message is returned. Bots can currently send animation files of up to 50 MB in size, this limit may be changed in the future.

#### Parameters

| Parameter | Type | Required | Description |
| --- | --- | --- | --- |
| business_connection_id | String | Optional | Unique identifier of the business connection on behalf of which the message will be sent |
| chat_id | Integer or String | Yes | Unique identifier for the target chat or username of the target bot, supergroup or channel in the format @username |
| message_thread_id | Integer | Optional | Unique identifier for the target message thread (topic) of a forum; for forum supergroups and private chats of bots with forum topic mode enabled only |
| direct_messages_topic_id | Integer | Optional | Identifier of the direct messages topic to which the message will be sent; required if the message is sent to a direct messages chat |
| ephemeral_message_parameters | EphemeralMessageParameters | Optional | A JSON-serialized object containing the parameters of the ephemeral message to send |
| animation | InputFile or String | Yes | Animation to send. Pass a file_id as String to send an animation that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get an animation from the Internet, or upload a new animation using multipart/form-data. More information on Sending Files » |
| duration | Integer | Optional | Duration of sent animation in seconds |
| width | Integer | Optional | Animation width |
| height | Integer | Optional | Animation height |
| thumbnail | InputFile or String | Optional | Thumbnail of the file sent; can be ignored if thumbnail generation for the file is supported server-side. The thumbnail should be in JPEG format and less than 200 kB in size. A thumbnail's width and height should not exceed 320. Ignored if the file is not uploaded using multipart/form-data. Thumbnails can't be reused and can be only uploaded as a new file, so you can pass "attach://<file_attach_name>" if the thumbnail was uploaded using multipart/form-data under <file_attach_name>. More information on Sending Files » |
| caption | String | Optional | Animation caption (may also be used when resending animation by file_id), 0-1024 characters after entities parsing |
| parse_mode | String | Optional | Mode for parsing entities in the animation caption. See formatting options for more details. |
| caption_entities | Array of MessageEntity | Optional | A JSON-serialized list of special entities that appear in the caption, which can be specified instead of parse_mode |
| show_caption_above_media | Boolean | Optional | Pass True if the caption must be shown above the message media |
| has_spoiler | Boolean | Optional | Pass True if the animation needs to be covered with a spoiler animation |
| disable_notification | Boolean | Optional | Sends the message silently. Users will receive a notification with no sound. |
| protect_content | Boolean | Optional | Protects the contents of the sent message from forwarding and saving |
| allow_paid_broadcast | Boolean | Optional | Pass True to allow up to 1000 messages per second, ignoring broadcasting limits for a fee of 0.1 Telegram Stars per message. The relevant Stars will be withdrawn from the bot's balance. |
| message_effect_id | String | Optional | Unique identifier of the message effect to be added to the message; for private chats only |
| suggested_post_parameters | SuggestedPostParameters | Optional | A JSON-serialized object containing the parameters of the suggested post to send; for direct messages chats only. If the message is sent as a reply to another suggested post, then that suggested post is automatically declined. |
| reply_parameters | ReplyParameters | Optional | Description of the message to reply to |
| reply_markup | InlineKeyboardMarkup or ReplyKeyboardMarkup or ReplyKeyboardRemove or ForceReply | Optional | Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove a reply keyboard or to force a reply from the user. |

#### Example

```php

```

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 12.130. sendAudio

> Use this method to send audio files, if you want Telegram clients to display them in the music player

Use this method to send audio files, if you want Telegram clients to display them in the music player. Your audio must be in the .MP3 or .M4A format. On success, the sent Message is returned. Bots can currently send audio files of up to 50 MB in size, this limit may be changed in the future.

For sending voice messages, use the sendVoice method instead.

#### Parameters

| Parameter | Type | Required | Description |
| --- | --- | --- | --- |
| business_connection_id | String | Optional | Unique identifier of the business connection on behalf of which the message will be sent |
| chat_id | Integer or String | Yes | Unique identifier for the target chat or username of the target bot, supergroup or channel in the format @username |
| message_thread_id | Integer | Optional | Unique identifier for the target message thread (topic) of a forum; for forum supergroups and private chats of bots with forum topic mode enabled only |
| direct_messages_topic_id | Integer | Optional | Identifier of the direct messages topic to which the message will be sent; required if the message is sent to a direct messages chat |
| ephemeral_message_parameters | EphemeralMessageParameters | Optional | A JSON-serialized object containing the parameters of the ephemeral message to send |
| audio | InputFile or String | Yes | Audio file to send. Pass a file_id as String to send an audio file that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get an audio file from the Internet, or upload a new one using multipart/form-data. More information on Sending Files » |
| caption | String | Optional | Audio caption, 0-1024 characters after entities parsing |
| parse_mode | String | Optional | Mode for parsing entities in the audio caption. See formatting options for more details. |
| caption_entities | Array of MessageEntity | Optional | A JSON-serialized list of special entities that appear in the caption, which can be specified instead of parse_mode |
| duration | Integer | Optional | Duration of the audio in seconds |
| performer | String | Optional | Performer |
| title | String | Optional | Track name |
| thumbnail | InputFile or String | Optional | Thumbnail of the file sent; can be ignored if thumbnail generation for the file is supported server-side. The thumbnail should be in JPEG format and less than 200 kB in size. A thumbnail's width and height should not exceed 320. Ignored if the file is not uploaded using multipart/form-data. Thumbnails can't be reused and can be only uploaded as a new file, so you can pass "attach://<file_attach_name>" if the thumbnail was uploaded using multipart/form-data under <file_attach_name>. More information on Sending Files » |
| disable_notification | Boolean | Optional | Sends the message silently. Users will receive a notification with no sound. |
| protect_content | Boolean | Optional | Protects the contents of the sent message from forwarding and saving |
| allow_paid_broadcast | Boolean | Optional | Pass True to allow up to 1000 messages per second, ignoring broadcasting limits for a fee of 0.1 Telegram Stars per message. The relevant Stars will be withdrawn from the bot's balance. |
| message_effect_id | String | Optional | Unique identifier of the message effect to be added to the message; for private chats only |
| suggested_post_parameters | SuggestedPostParameters | Optional | A JSON-serialized object containing the parameters of the suggested post to send; for direct messages chats only. If the message is sent as a reply to another suggested post, then that suggested post is automatically declined. |
| reply_parameters | ReplyParameters | Optional | Description of the message to reply to |
| reply_markup | InlineKeyboardMarkup or ReplyKeyboardMarkup or ReplyKeyboardRemove or ForceReply | Optional | Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove a reply keyboard or to force a reply from the user. |

#### Example

```php

```

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 12.131. sendChatAction

> Use this method when you need to tell the user that something is happening on the bot's side

Use this method when you need to tell the user that something is happening on the bot's side. The status is set for 5 seconds or less (when a message arrives from your bot, Telegram clients clear its typing status). Returns *True* on success.

Example: The ImageBot needs some time to process a request and upload the image. Instead of sending a text message along the lines of "Retrieving image, please wait...", the bot may use sendChatAction with *action* = *upload_photo*. The user will see a "sending photo" status for the bot.

We only recommend using this method when a response from the bot will take a **noticeable** amount of time to arrive.

#### Parameters

| Parameter | Type | Required | Description |
| --- | --- | --- | --- |
| business_connection_id | String | Optional | Unique identifier of the business connection on behalf of which the action will be sent |
| chat_id | Integer or String | Yes | Unique identifier for the target chat or username of the target bot or supergroup in the format @username. Channel chats and channel direct messages chats aren't supported. |
| message_thread_id | Integer | Optional | Unique identifier for the target message thread or topic of a forum; for supergroups and private chats of bots with forum topic mode enabled only |
| action | String | Yes | Type of action to broadcast. Choose one, depending on what the user is about to receive: typing for text messages, upload_photo for photos, record_video or upload_video for videos, record_voice or upload_voice for voice notes, upload_document for general files, choose_sticker for stickers, find_location for location data, record_video_note or upload_video_note for video notes. |

#### Example

```php

```

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 12.132. sendChatJoinRequestWebApp

> Use this method to process a received chat join request query by showing a Mini App to the user before deciding the outcome

Use this method to process a received chat join request query by showing a Mini App to the user before deciding the outcome. Call answerChatJoinRequestQuery to resolve the join request query based on the user interaction with the Mini App. Returns *True* on success.

#### Parameters

| Parameter | Type | Required | Description |
| --- | --- | --- | --- |
| chat_join_request_query_id | String | Yes | Unique identifier of the join request query |
| web_app_url | String | Yes | An HTTPS URL of a Web App to be opened with additional data as specified in Initializing Web Apps |

#### Example

```php

```

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 12.133. sendChecklist

> Use this method to send a checklist on behalf of a connected business account

Use this method to send a checklist on behalf of a connected business account. On success, the sent Message is returned.

#### Parameters

| Parameter | Type | Required | Description |
| --- | --- | --- | --- |
| business_connection_id | String | Yes | Unique identifier of the business connection on behalf of which the message will be sent |
| chat_id | Integer or String | Yes | Unique identifier for the target chat or username of the target bot in the format @username |
| checklist | InputChecklist | Yes | A JSON-serialized object for the checklist to send |
| disable_notification | Boolean | Optional | Sends the message silently. Users will receive a notification with no sound. |
| protect_content | Boolean | Optional | Protects the contents of the sent message from forwarding and saving |
| message_effect_id | String | Optional | Unique identifier of the message effect to be added to the message |
| reply_parameters | ReplyParameters | Optional | A JSON-serialized object for description of the message to reply to |
| reply_markup | InlineKeyboardMarkup | Optional | A JSON-serialized object for an inline keyboard |

#### Example

```php

```

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 12.134. sendContact

> Use this method to send phone contacts

Use this method to send phone contacts. On success, the sent Message is returned.

#### Parameters

| Parameter | Type | Required | Description |
| --- | --- | --- | --- |
| business_connection_id | String | Optional | Unique identifier of the business connection on behalf of which the message will be sent |
| chat_id | Integer or String | Yes | Unique identifier for the target chat or username of the target bot, supergroup or channel in the format @username |
| message_thread_id | Integer | Optional | Unique identifier for the target message thread (topic) of a forum; for forum supergroups and private chats of bots with forum topic mode enabled only |
| direct_messages_topic_id | Integer | Optional | Identifier of the direct messages topic to which the message will be sent; required if the message is sent to a direct messages chat |
| ephemeral_message_parameters | EphemeralMessageParameters | Optional | A JSON-serialized object containing the parameters of the ephemeral message to send |
| phone_number | String | Yes | Contact's phone number |
| first_name | String | Yes | Contact's first name |
| last_name | String | Optional | Contact's last name |
| vcard | String | Optional | Additional data about the contact in the form of a vCard, 0-2048 bytes |
| disable_notification | Boolean | Optional | Sends the message silently. Users will receive a notification with no sound. |
| protect_content | Boolean | Optional | Protects the contents of the sent message from forwarding and saving |
| allow_paid_broadcast | Boolean | Optional | Pass True to allow up to 1000 messages per second, ignoring broadcasting limits for a fee of 0.1 Telegram Stars per message. The relevant Stars will be withdrawn from the bot's balance. |
| message_effect_id | String | Optional | Unique identifier of the message effect to be added to the message; for private chats only |
| suggested_post_parameters | SuggestedPostParameters | Optional | A JSON-serialized object containing the parameters of the suggested post to send; for direct messages chats only. If the message is sent as a reply to another suggested post, then that suggested post is automatically declined. |
| reply_parameters | ReplyParameters | Optional | Description of the message to reply to |
| reply_markup | InlineKeyboardMarkup or ReplyKeyboardMarkup or ReplyKeyboardRemove or ForceReply | Optional | Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove a reply keyboard or to force a reply from the user. |

#### Example

```php

```

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 12.135. sendDice

> Use this method to send an animated emoji that will display a random value

Use this method to send an animated emoji that will display a random value. On success, the sent Message is returned.

#### Parameters

| Parameter | Type | Required | Description |
| --- | --- | --- | --- |
| business_connection_id | String | Optional | Unique identifier of the business connection on behalf of which the message will be sent |
| chat_id | Integer or String | Yes | Unique identifier for the target chat or username of the target bot, supergroup or channel in the format @username |
| message_thread_id | Integer | Optional | Unique identifier for the target message thread (topic) of a forum; for forum supergroups and private chats of bots with forum topic mode enabled only |
| direct_messages_topic_id | Integer | Optional | Identifier of the direct messages topic to which the message will be sent; required if the message is sent to a direct messages chat |
| emoji | String | Optional | Emoji on which the dice throw animation is based. Currently, must be one of "🎲", "🎯", "🏀", "⚽", "🎳", or "🎰". Dice can have values 1-6 for "🎲", "🎯" and "🎳", values 1-5 for "🏀" and "⚽", and values 1-64 for "🎰". Defaults to "🎲". |
| disable_notification | Boolean | Optional | Sends the message silently. Users will receive a notification with no sound. |
| protect_content | Boolean | Optional | Protects the contents of the sent message from forwarding |
| allow_paid_broadcast | Boolean | Optional | Pass True to allow up to 1000 messages per second, ignoring broadcasting limits for a fee of 0.1 Telegram Stars per message. The relevant Stars will be withdrawn from the bot's balance. |
| message_effect_id | String | Optional | Unique identifier of the message effect to be added to the message; for private chats only |
| suggested_post_parameters | SuggestedPostParameters | Optional | A JSON-serialized object containing the parameters of the suggested post to send; for direct messages chats only. If the message is sent as a reply to another suggested post, then that suggested post is automatically declined. |
| reply_parameters | ReplyParameters | Optional | Description of the message to reply to |
| reply_markup | InlineKeyboardMarkup or ReplyKeyboardMarkup or ReplyKeyboardRemove or ForceReply | Optional | Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove a reply keyboard or to force a reply from the user. |

#### Example

```php

```

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 12.136. sendDocument

> Use this method to send general files

**Botlify Native Shorthand:**

  `tg_send_media('document', $chatId, $filePath, $caption);`

  Attaches local files (database.db, logs) or remote files to chat. See [Native Helpers Guide](?page=tg-native-helpers).
 

Use this method to send general files. On success, the sent Message is returned. Bots can currently send files of any type of up to 50 MB in size, this limit may be changed in the future.

#### Parameters

| Parameter | Type | Required | Description |
| --- | --- | --- | --- |
| business_connection_id | String | Optional | Unique identifier of the business connection on behalf of which the message will be sent |
| chat_id | Integer or String | Yes | Unique identifier for the target chat or username of the target bot, supergroup or channel in the format @username |
| message_thread_id | Integer | Optional | Unique identifier for the target message thread (topic) of a forum; for forum supergroups and private chats of bots with forum topic mode enabled only |
| direct_messages_topic_id | Integer | Optional | Identifier of the direct messages topic to which the message will be sent; required if the message is sent to a direct messages chat |
| ephemeral_message_parameters | EphemeralMessageParameters | Optional | A JSON-serialized object containing the parameters of the ephemeral message to send |
| document | InputFile or String | Yes | File to send. Pass a file_id as String to send a file that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a file from the Internet, or upload a new one using multipart/form-data. More information on Sending Files » |
| thumbnail | InputFile or String | Optional | Thumbnail of the file sent; can be ignored if thumbnail generation for the file is supported server-side. The thumbnail should be in JPEG format and less than 200 kB in size. A thumbnail's width and height should not exceed 320. Ignored if the file is not uploaded using multipart/form-data. Thumbnails can't be reused and can be only uploaded as a new file, so you can pass "attach://<file_attach_name>" if the thumbnail was uploaded using multipart/form-data under <file_attach_name>. More information on Sending Files » |
| caption | String | Optional | Document caption (may also be used when resending documents by file_id), 0-1024 characters after entities parsing |
| parse_mode | String | Optional | Mode for parsing entities in the document caption. See formatting options for more details. |
| caption_entities | Array of MessageEntity | Optional | A JSON-serialized list of special entities that appear in the caption, which can be specified instead of parse_mode |
| disable_content_type_detection | Boolean | Optional | Disables automatic server-side content type detection for files uploaded using multipart/form-data |
| disable_notification | Boolean | Optional | Sends the message silently. Users will receive a notification with no sound. |
| protect_content | Boolean | Optional | Protects the contents of the sent message from forwarding and saving |
| allow_paid_broadcast | Boolean | Optional | Pass True to allow up to 1000 messages per second, ignoring broadcasting limits for a fee of 0.1 Telegram Stars per message. The relevant Stars will be withdrawn from the bot's balance. |
| message_effect_id | String | Optional | Unique identifier of the message effect to be added to the message; for private chats only |
| suggested_post_parameters | SuggestedPostParameters | Optional | A JSON-serialized object containing the parameters of the suggested post to send; for direct messages chats only. If the message is sent as a reply to another suggested post, then that suggested post is automatically declined. |
| reply_parameters | ReplyParameters | Optional | Description of the message to reply to |
| reply_markup | InlineKeyboardMarkup or ReplyKeyboardMarkup or ReplyKeyboardRemove or ForceReply | Optional | Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove a reply keyboard or to force a reply from the user. |

#### Example

```php

```

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 12.137. sendGame

> Use this method to send a game

Use this method to send a game. On success, the sent Message is returned.

#### Parameters

| Parameter | Type | Required | Description |
| --- | --- | --- | --- |
| business_connection_id | String | Optional | Unique identifier of the business connection on behalf of which the message will be sent |
| chat_id | Integer or String | Yes | Unique identifier for the target chat or username of the target bot in the format @username. Games can't be sent to channel direct messages chats and channel chats. |
| message_thread_id | Integer | Optional | Unique identifier for the target message thread (topic) of a forum; for forum supergroups and private chats of bots with forum topic mode enabled only |
| game_short_name | String | Yes | Short name of the game, serves as the unique identifier for the game. Set up your games via @BotFather. |
| disable_notification | Boolean | Optional | Sends the message silently. Users will receive a notification with no sound. |
| protect_content | Boolean | Optional | Protects the contents of the sent message from forwarding and saving |
| allow_paid_broadcast | Boolean | Optional | Pass True to allow up to 1000 messages per second, ignoring broadcasting limits for a fee of 0.1 Telegram Stars per message. The relevant Stars will be withdrawn from the bot's balance. |
| message_effect_id | String | Optional | Unique identifier of the message effect to be added to the message; for private chats only |
| reply_parameters | ReplyParameters | Optional | Description of the message to reply to |
| reply_markup | InlineKeyboardMarkup | Optional | A JSON-serialized object for an inline keyboard. If empty, one 'Play game_title' button will be shown. If not empty, the first button must launch the game. |

#### Example

```php

```

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 12.138. sendGift

> Sends a gift to the given user or channel chat

Sends a gift to the given user or channel chat. The gift can't be converted to Telegram Stars by the receiver. Returns *True* on success.

#### Parameters

| Parameter | Type | Required | Description |
| --- | --- | --- | --- |
| user_id | Integer | Optional | Required if chat_id is not specified. Unique identifier of the target user who will receive the gift. |
| chat_id | Integer or String | Optional | Required if user_id is not specified. Unique identifier for the chat or username of the channel (in the format @username) that will receive the gift. |
| gift_id | String | Yes | Identifier of the gift; limited gifts can't be sent to channel chats |
| pay_for_upgrade | Boolean | Optional | Pass True to pay for the gift upgrade from the bot's balance, thereby making the upgrade free for the receiver |
| text | String | Optional | Text that will be shown along with the gift; 0-128 characters |
| text_parse_mode | String | Optional | Mode for parsing entities in the text. See formatting options for more details. Entities other than "bold", "italic", "underline", "strikethrough", "spoiler", "custom_emoji", and "date_time" are ignored. |
| text_entities | Array of MessageEntity | Optional | A JSON-serialized list of special entities that appear in the gift text. It can be specified instead of text_parse_mode. Entities other than "bold", "italic", "underline", "strikethrough", "spoiler", "custom_emoji", and "date_time" are ignored. |

#### Example

```php

```

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 12.139. sendInvoice

> Use this method to send invoices

Use this method to send invoices. On success, the sent Message is returned.

#### Parameters

| Parameter | Type | Required | Description |
| --- | --- | --- | --- |
| chat_id | Integer or String | Yes | Unique identifier for the target chat or username of the target bot, supergroup or channel in the format @username |
| message_thread_id | Integer | Optional | Unique identifier for the target message thread (topic) of a forum; for forum supergroups and private chats of bots with forum topic mode enabled only |
| direct_messages_topic_id | Integer | Optional | Identifier of the direct messages topic to which the message will be sent; required if the message is sent to a direct messages chat |
| title | String | Yes | Product name, 1-32 characters |
| description | String | Yes | Product description, 1-255 characters |
| payload | String | Yes | Bot-defined invoice payload, 1-128 bytes. This will not be displayed to the user, use it for your internal processes. |
| provider_token | String | Optional | Payment provider token, obtained via @BotFather. Pass an empty string for payments in Telegram Stars. |
| currency | String | Yes | Three-letter ISO 4217 currency code, see more on currencies. Pass "XTR" for payments in Telegram Stars. |
| prices | Array of LabeledPrice | Yes | Price breakdown, a JSON-serialized list of components (e.g. product price, tax, discount, delivery cost, delivery tax, bonus, etc.). Must contain exactly one item for payments in Telegram Stars. |
| max_tip_amount | Integer | Optional | The maximum accepted amount for tips in the smallest units of the currency (integer, not float/double). For example, for a maximum tip of US$ 1.45 pass max_tip_amount = 145. See the exp parameter in currencies.json, it shows the number of digits past the decimal point for each currency (2 for the majority of currencies). Defaults to 0. Not supported for payments in Telegram Stars. |
| suggested_tip_amounts | Array of Integer | Optional | A JSON-serialized Array of suggested amounts of tips in the smallest units of the currency (integer, not float/double). At most 4 suggested tip amounts can be specified. The suggested tip amounts must be positive, passed in a strictly increased order and must not exceed max_tip_amount. |
| start_parameter | String | Optional | Unique deep-linking parameter. If left empty, forwarded copies of the sent message will have a Pay button, allowing multiple users to pay directly from the forwarded message, using the same invoice. If non-empty, forwarded copies of the sent message will have a URL button with a deep link to the bot (instead of a Pay button), with the value used as the start parameter. |
| provider_data | String | Optional | JSON-serialized data about the invoice, which will be shared with the payment provider. A detailed description of required fields should be provided by the payment provider. |
| photo_url | String | Optional | URL of the product photo for the invoice. Can be a photo of the goods or a marketing image for a service. People like it better when they see what they are paying for. |
| photo_size | Integer | Optional | Photo size in bytes |
| photo_width | Integer | Optional | Photo width |
| photo_height | Integer | Optional | Photo height |
| need_name | Boolean | Optional | Pass True if you require the user's full name to complete the order. Ignored for payments in Telegram Stars. |
| need_phone_number | Boolean | Optional | Pass True if you require the user's phone number to complete the order. Ignored for payments in Telegram Stars. |
| need_email | Boolean | Optional | Pass True if you require the user's email address to complete the order. Ignored for payments in Telegram Stars. |
| need_shipping_address | Boolean | Optional | Pass True if you require the user's shipping address to complete the order. Ignored for payments in Telegram Stars. |
| send_phone_number_to_provider | Boolean | Optional | Pass True if the user's phone number should be sent to the provider. Ignored for payments in Telegram Stars. |
| send_email_to_provider | Boolean | Optional | Pass True if the user's email address should be sent to the provider. Ignored for payments in Telegram Stars. |
| is_flexible | Boolean | Optional | Pass True if the final price depends on the shipping method. Ignored for payments in Telegram Stars. |
| disable_notification | Boolean | Optional | Sends the message silently. Users will receive a notification with no sound. |
| protect_content | Boolean | Optional | Protects the contents of the sent message from forwarding and saving |
| allow_paid_broadcast | Boolean | Optional | Pass True to allow up to 1000 messages per second, ignoring broadcasting limits for a fee of 0.1 Telegram Stars per message. The relevant Stars will be withdrawn from the bot's balance. |
| message_effect_id | String | Optional | Unique identifier of the message effect to be added to the message; for private chats only |
| suggested_post_parameters | SuggestedPostParameters | Optional | A JSON-serialized object containing the parameters of the suggested post to send; for direct messages chats only. If the message is sent as a reply to another suggested post, then that suggested post is automatically declined. |
| reply_parameters | ReplyParameters | Optional | Description of the message to reply to |
| reply_markup | InlineKeyboardMarkup | Optional | A JSON-serialized object for an inline keyboard. If empty, one 'Pay total price' button will be shown. If not empty, the first button must be a Pay button. |

#### Example

```php

```

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 12.140. sendLivePhoto

> Use this method to send live photos

Use this method to send live photos. On success, the sent Message is returned.

#### Parameters

| Parameter | Type | Required | Description |
| --- | --- | --- | --- |
| business_connection_id | String | Optional | Unique identifier of the business connection on behalf of which the message will be sent |
| chat_id | Integer or String | Yes | Unique identifier for the target chat or username of the target channel (in the format @channelusername) |
| message_thread_id | Integer | Optional | Unique identifier for the target message thread (topic) of a forum; for forum supergroups and private chats of bots with forum topic mode enabled only |
| direct_messages_topic_id | Integer | Optional | Identifier of the direct messages topic to which the message will be sent; required if the message is sent to a direct messages chat |
| ephemeral_message_parameters | EphemeralMessageParameters | Optional | A JSON-serialized object containing the parameters of the ephemeral message to send |
| live_photo | InputFile or String | Yes | Live photo video to send. The video must be no longer than 10 seconds and must not exceed 10 MB in size. Pass a file_id as String to send a video that exists on the Telegram servers (recommended) or upload a new video using multipart/form-data. More information on Sending Files ». Sending live photos by a URL is currently unsupported. |
| photo | InputFile or String | Yes | The static photo to send. Pass a file_id as String to send a photo that exists on the Telegram servers (recommended) or upload a new video using multipart/form-data. More information on Sending Files ». Sending live photos by a URL is currently unsupported. |
| caption | String | Optional | Video caption (may also be used when resending videos by file_id), 0-1024 characters after entities parsing |
| parse_mode | String | Optional | Mode for parsing entities in the video caption. See formatting options for more details. |
| caption_entities | Array of MessageEntity | Optional | A JSON-serialized list of special entities that appear in the caption, which can be specified instead of parse_mode |
| show_caption_above_media | Boolean | Optional | Pass True if the caption must be shown above the message media |
| has_spoiler | Boolean | Optional | Pass True if the video needs to be covered with a spoiler animation |
| disable_notification | Boolean | Optional | Sends the message silently. Users will receive a notification with no sound. |
| protect_content | Boolean | Optional | Protects the contents of the sent message from forwarding and saving |
| allow_paid_broadcast | Boolean | Optional | Pass True to allow up to 1000 messages per second, ignoring broadcasting limits for a fee of 0.1 Telegram Stars per message. The relevant Stars will be withdrawn from the bot's balance. |
| message_effect_id | String | Optional | Unique identifier of the message effect to be added to the message; for private chats only |
| suggested_post_parameters | SuggestedPostParameters | Optional | A JSON-serialized object containing the parameters of the suggested post to send; for direct messages chats only. If the message is sent as a reply to another suggested post, then that suggested post is automatically declined. |
| reply_parameters | ReplyParameters | Optional | Description of the message to reply to |
| reply_markup | InlineKeyboardMarkup or ReplyKeyboardMarkup or ReplyKeyboardRemove or ForceReply | Optional | Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove a reply keyboard or to force a reply from the user. |

#### Example

```php

```

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 12.141. sendLocation

> Use this method to send point on the map

Use this method to send point on the map. On success, the sent Message is returned.

#### Parameters

| Parameter | Type | Required | Description |
| --- | --- | --- | --- |
| business_connection_id | String | Optional | Unique identifier of the business connection on behalf of which the message will be sent |
| chat_id | Integer or String | Yes | Unique identifier for the target chat or username of the target bot, supergroup or channel in the format @username |
| message_thread_id | Integer | Optional | Unique identifier for the target message thread (topic) of a forum; for forum supergroups and private chats of bots with forum topic mode enabled only |
| direct_messages_topic_id | Integer | Optional | Identifier of the direct messages topic to which the message will be sent; required if the message is sent to a direct messages chat |
| ephemeral_message_parameters | EphemeralMessageParameters | Optional | A JSON-serialized object containing the parameters of the ephemeral message to send |
| latitude | Float | Yes | Latitude of the location |
| longitude | Float | Yes | Longitude of the location |
| horizontal_accuracy | Float | Optional | The radius of uncertainty for the location, measured in meters; 0-1500 |
| live_period | Integer | Optional | Period in seconds during which the location will be updated (see Live Locations), must be between 60 and 86400, or 0x7FFFFFFF for live locations that can be edited indefinitely. Must be 0 for ephemeral messages. |
| heading | Integer | Optional | For live locations, a direction in which the user is moving, in degrees. Must be between 1 and 360 if specified. |
| proximity_alert_radius | Integer | Optional | For live locations, a maximum distance for proximity alerts about approaching another chat member, in meters. Must be between 1 and 100000 if specified. |
| disable_notification | Boolean | Optional | Sends the message silently. Users will receive a notification with no sound. |
| protect_content | Boolean | Optional | Protects the contents of the sent message from forwarding and saving |
| allow_paid_broadcast | Boolean | Optional | Pass True to allow up to 1000 messages per second, ignoring broadcasting limits for a fee of 0.1 Telegram Stars per message. The relevant Stars will be withdrawn from the bot's balance. |
| message_effect_id | String | Optional | Unique identifier of the message effect to be added to the message; for private chats only |
| suggested_post_parameters | SuggestedPostParameters | Optional | A JSON-serialized object containing the parameters of the suggested post to send; for direct messages chats only. If the message is sent as a reply to another suggested post, then that suggested post is automatically declined. |
| reply_parameters | ReplyParameters | Optional | Description of the message to reply to |
| reply_markup | InlineKeyboardMarkup or ReplyKeyboardMarkup or ReplyKeyboardRemove or ForceReply | Optional | Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove a reply keyboard or to force a reply from the user. |

#### Example

```php

```

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 12.142. sendMediaGroup

> Use this method to send a group of photos, live photos, videos, documents or audios as an album

Use this method to send a group of photos, live photos, videos, documents or audios as an album. Documents and audio files can be only grouped in an album with messages of the same type. On success, an Array of Message objects that were sent is returned.

#### Parameters

| Parameter | Type | Required | Description |
| --- | --- | --- | --- |
| business_connection_id | String | Optional | Unique identifier of the business connection on behalf of which the message will be sent |
| chat_id | Integer or String | Yes | Unique identifier for the target chat or username of the target bot, supergroup or channel in the format @username |
| message_thread_id | Integer | Optional | Unique identifier for the target message thread (topic) of a forum; for forum supergroups and private chats of bots with forum topic mode enabled only |
| direct_messages_topic_id | Integer | Optional | Identifier of the direct messages topic to which the messages will be sent; required if the messages are sent to a direct messages chat |
| media | Array of InputMediaAudio, InputMediaDocument, InputMediaLivePhoto, InputMediaPhoto and InputMediaVideo | Yes | A JSON-serialized Array describing messages to be sent, must include 2-10 items |
| disable_notification | Boolean | Optional | Sends messages silently. Users will receive a notification with no sound. |
| protect_content | Boolean | Optional | Protects the contents of the sent messages from forwarding and saving |
| allow_paid_broadcast | Boolean | Optional | Pass True to allow up to 1000 messages per second, ignoring broadcasting limits for a fee of 0.1 Telegram Stars per message. The relevant Stars will be withdrawn from the bot's balance. |
| message_effect_id | String | Optional | Unique identifier of the message effect to be added to the message; for private chats only |
| reply_parameters | ReplyParameters | Optional | Description of the message to reply to |

#### Example

```php

```

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 12.143. sendMessage

> Use this method to send text messages

**Botlify Native Shorthand:**

  `tg_send($chatId, $text, $extra);`

  Fastest way to send formatted HTML messages in Botlify Cloud without manually constructing arrays. See [Native Helpers Guide](?page=tg-native-helpers).
 

Use this method to send text messages. On success, the sent Message is returned.

#### Parameters

| Parameter | Type | Required | Description |
| --- | --- | --- | --- |
| business_connection_id | String | Optional | Unique identifier of the business connection on behalf of which the message will be sent |
| chat_id | Integer or String | Yes | Unique identifier for the target chat or username of the target bot, supergroup or channel in the format @username |
| message_thread_id | Integer | Optional | Unique identifier for the target message thread (topic) of a forum; for forum supergroups and private chats of bots with forum topic mode enabled only |
| direct_messages_topic_id | Integer | Optional | Identifier of the direct messages topic to which the message will be sent; required if the message is sent to a direct messages chat |
| ephemeral_message_parameters | EphemeralMessageParameters | Optional | A JSON-serialized object containing the parameters of the ephemeral message to send |
| text | String | Yes | Text of the message to be sent, 1-4096 characters after entities parsing |
| parse_mode | String | Optional | Mode for parsing entities in the message text. See formatting options for more details. |
| entities | Array of MessageEntity | Optional | A JSON-serialized list of special entities that appear in message text, which can be specified instead of parse_mode |
| link_preview_options | LinkPreviewOptions | Optional | Link preview generation options for the message |
| disable_notification | Boolean | Optional | Sends the message silently. Users will receive a notification with no sound. |
| protect_content | Boolean | Optional | Protects the contents of the sent message from forwarding and saving |
| allow_paid_broadcast | Boolean | Optional | Pass True to allow up to 1000 messages per second, ignoring broadcasting limits for a fee of 0.1 Telegram Stars per message. The relevant Stars will be withdrawn from the bot's balance. |
| message_effect_id | String | Optional | Unique identifier of the message effect to be added to the message; for private chats only |
| suggested_post_parameters | SuggestedPostParameters | Optional | A JSON-serialized object containing the parameters of the suggested post to send; for direct messages chats only. If the message is sent as a reply to another suggested post, then that suggested post is automatically declined. |
| reply_parameters | ReplyParameters | Optional | Description of the message to reply to |
| reply_markup | InlineKeyboardMarkup or ReplyKeyboardMarkup or ReplyKeyboardRemove or ForceReply | Optional | Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove a reply keyboard or to force a reply from the user. |

#### Example

```php

```

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 12.144. sendMessageDraft

> Use this method to stream a partial message to a user while the message is being generated

Use this method to stream a partial message to a user while the message is being generated. Note that the streamed draft is ephemeral and acts as a temporary 30-second preview - once the output is finalized, you **must** call sendMessage with the complete message to persist it in the user's chat. Returns *True* on success.

#### Parameters

| Parameter | Type | Required | Description |
| --- | --- | --- | --- |
| chat_id | Integer | Yes | Unique identifier for the target private chat |
| message_thread_id | Integer | Optional | Unique identifier for the target message thread |
| draft_id | Integer | Yes | Unique identifier of the message draft; must be non-zero. Changes to drafts with the same identifier are animated. Otherwise, the draft is replaced without animation. |
| text | String | Optional | Text of the message to be sent, 0-4096 characters after entities parsing. Pass an empty text to show a "Thinking..." placeholder. |
| parse_mode | String | Optional | Mode for parsing entities in the message text. See formatting options for more details. |
| entities | Array of MessageEntity | Optional | A JSON-serialized list of special entities that appear in message text, which can be specified instead of parse_mode |
| can_stop | Boolean | Optional | Pass True to show the user a button to stop further drafts. The bot will receive an Update "stopped_message_generation" if the user presses the button. |
| keep_on_stop | Boolean | Optional | Pass True to keep the draft in the chat when the button is pressed. The draft will still disappear after a short time or if the bot sends a message. To fully preserve the partial draft, the bot should send it as a new message. |

#### Example

```php

```

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 12.145. sendPaidMedia

> Use this method to send paid media

Use this method to send paid media. On success, the sent Message is returned.

#### Parameters

| Parameter | Type | Required | Description |
| --- | --- | --- | --- |
| business_connection_id | String | Optional | Unique identifier of the business connection on behalf of which the message will be sent |
| chat_id | Integer or String | Yes | Unique identifier for the target chat or username of the target bot, supergroup or channel in the format @username. If the chat is a channel, all Telegram Star proceeds from this media will be credited to the chat's balance. Otherwise, they will be credited to the bot's balance. |
| message_thread_id | Integer | Optional | Unique identifier for the target message thread (topic) of a forum; for forum supergroups and private chats of bots with forum topic mode enabled only |
| direct_messages_topic_id | Integer | Optional | Identifier of the direct messages topic to which the message will be sent; required if the message is sent to a direct messages chat |
| star_count | Integer | Yes | The number of Telegram Stars that must be paid to buy access to the media; 1-25000 |
| media | Array of InputPaidMedia | Yes | A JSON-serialized Array describing the media to be sent; up to 10 items |
| payload | String | Optional | Bot-defined paid media payload, 0-128 bytes. This will not be displayed to the user, use it for your internal processes. |
| caption | String | Optional | Media caption, 0-1024 characters after entities parsing |
| parse_mode | String | Optional | Mode for parsing entities in the media caption. See formatting options for more details. |
| caption_entities | Array of MessageEntity | Optional | A JSON-serialized list of special entities that appear in the caption, which can be specified instead of parse_mode |
| show_caption_above_media | Boolean | Optional | Pass True if the caption must be shown above the message media |
| disable_notification | Boolean | Optional | Sends the message silently. Users will receive a notification with no sound. |
| protect_content | Boolean | Optional | Protects the contents of the sent message from forwarding and saving |
| allow_paid_broadcast | Boolean | Optional | Pass True to allow up to 1000 messages per second, ignoring broadcasting limits for a fee of 0.1 Telegram Stars per message. The relevant Stars will be withdrawn from the bot's balance. |
| suggested_post_parameters | SuggestedPostParameters | Optional | A JSON-serialized object containing the parameters of the suggested post to send; for direct messages chats only. If the message is sent as a reply to another suggested post, then that suggested post is automatically declined. |
| reply_parameters | ReplyParameters | Optional | Description of the message to reply to |
| reply_markup | InlineKeyboardMarkup or ReplyKeyboardMarkup or ReplyKeyboardRemove or ForceReply | Optional | Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove a reply keyboard or to force a reply from the user. |

#### Example

```php

```

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 12.146. sendPhoto

> Use this method to send photos

**Botlify Native Shorthand:**

  `tg_send_media('photo', $chatId, $photoUrlOrPath, $caption);`

  Supports both remote image URLs and local filesystem paths seamlessly. See [Native Helpers Guide](?page=tg-native-helpers).
 

Use this method to send photos. On success, the sent Message is returned.

#### Parameters

| Parameter | Type | Required | Description |
| --- | --- | --- | --- |
| business_connection_id | String | Optional | Unique identifier of the business connection on behalf of which the message will be sent |
| chat_id | Integer or String | Yes | Unique identifier for the target chat or username of the target bot, supergroup or channel in the format @username |
| message_thread_id | Integer | Optional | Unique identifier for the target message thread (topic) of a forum; for forum supergroups and private chats of bots with forum topic mode enabled only |
| direct_messages_topic_id | Integer | Optional | Identifier of the direct messages topic to which the message will be sent; required if the message is sent to a direct messages chat |
| ephemeral_message_parameters | EphemeralMessageParameters | Optional | A JSON-serialized object containing the parameters of the ephemeral message to send |
| photo | InputFile or String | Yes | Photo to send. Pass a file_id as String to send a photo that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a photo from the Internet, or upload a new photo using multipart/form-data. The photo must be at most 10 MB in size. The photo's width and height must not exceed 10000 in total. Width and height ratio must be at most 20. More information on Sending Files » |
| caption | String | Optional | Photo caption (may also be used when resending photos by file_id), 0-1024 characters after entities parsing |
| parse_mode | String | Optional | Mode for parsing entities in the photo caption. See formatting options for more details. |
| caption_entities | Array of MessageEntity | Optional | A JSON-serialized list of special entities that appear in the caption, which can be specified instead of parse_mode |
| show_caption_above_media | Boolean | Optional | Pass True if the caption must be shown above the message media |
| has_spoiler | Boolean | Optional | Pass True if the photo needs to be covered with a spoiler animation |
| disable_notification | Boolean | Optional | Sends the message silently. Users will receive a notification with no sound. |
| protect_content | Boolean | Optional | Protects the contents of the sent message from forwarding and saving |
| allow_paid_broadcast | Boolean | Optional | Pass True to allow up to 1000 messages per second, ignoring broadcasting limits for a fee of 0.1 Telegram Stars per message. The relevant Stars will be withdrawn from the bot's balance. |
| message_effect_id | String | Optional | Unique identifier of the message effect to be added to the message; for private chats only |
| suggested_post_parameters | SuggestedPostParameters | Optional | A JSON-serialized object containing the parameters of the suggested post to send; for direct messages chats only. If the message is sent as a reply to another suggested post, then that suggested post is automatically declined. |
| reply_parameters | ReplyParameters | Optional | Description of the message to reply to |
| reply_markup | InlineKeyboardMarkup or ReplyKeyboardMarkup or ReplyKeyboardRemove or ForceReply | Optional | Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove a reply keyboard or to force a reply from the user. |

#### Example

```php

```

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 12.147. sendPoll

> Use this method to send a native poll

Use this method to send a native poll. On success, the sent Message is returned.

#### Parameters

| Parameter | Type | Required | Description |
| --- | --- | --- | --- |
| business_connection_id | String | Optional | Unique identifier of the business connection on behalf of which the message will be sent |
| chat_id | Integer or String | Yes | Unique identifier for the target chat or username of the target bot, supergroup or channel in the format @username. Polls can't be sent to channel direct messages chats. |
| message_thread_id | Integer | Optional | Unique identifier for the target message thread (topic) of a forum; for forum supergroups and private chats of bots with forum topic mode enabled only |
| question | String | Yes | Poll question, 1-300 characters |
| question_parse_mode | String | Optional | Mode for parsing entities in the question. See formatting options for more details. Currently, only custom emoji entities are allowed. |
| question_entities | Array of MessageEntity | Optional | A JSON-serialized list of special entities that appear in the poll question. It can be specified instead of question_parse_mode. |
| options | Array of InputPollOption | Yes | A JSON-serialized list of 1-12 answer options |
| is_anonymous | Boolean | Optional | True, if the poll needs to be anonymous, defaults to True |
| type | String | Optional | Poll type, "quiz" or "regular", defaults to "regular" |
| allows_multiple_answers | Boolean | Optional | Pass True if the poll allows multiple answers, defaults to False |
| allows_revoting | Boolean | Optional | Pass True if the poll allows to change chosen answer options, defaults to False for quizzes and to True for regular polls |
| shuffle_options | Boolean | Optional | Pass True if the poll options must be shown in random order |
| allow_adding_options | Boolean | Optional | Pass True if answer options can be added to the poll after creation; not supported for anonymous polls and quizzes |
| hide_results_until_closes | Boolean | Optional | Pass True if poll results must be shown only after the poll closes |
| members_only | Boolean | Optional | Pass True if voting is limited to users who have been members of the chat where the poll is being sent for more than 24 hours; for channel chats only |
| country_codes | Array of String | Optional | A JSON-serialized list of 0-12 two-letter ISO 3166-1 alpha-2 country codes indicating the countries from which users can vote in the poll; for channel chats only. Use "FT" as a country code to allow users with anonymous numbers to vote. If omitted or empty, then users from any country can participate in the poll. |
| correct_option_ids | Array of Integer | Optional | A JSON-serialized list of monotonically increasing 0-based identifiers of the correct answer options, required for polls in quiz mode |
| explanation | String | Optional | Text that is shown when a user chooses an incorrect answer or taps on the lamp icon in a quiz-style poll, 0-200 characters with at most 2 line feeds after entities parsing |
| explanation_parse_mode | String | Optional | Mode for parsing entities in the explanation. See formatting options for more details. |
| explanation_entities | Array of MessageEntity | Optional | A JSON-serialized list of special entities that appear in the poll explanation. It can be specified instead of explanation_parse_mode. |
| explanation_media | InputPollMedia | Optional | Media added to the quiz explanation |
| open_period | Integer | Optional | Amount of time in seconds the poll will be active after creation, 5-2628000. Can't be used together with close_date. |
| close_date | Integer | Optional | Point in time (Unix timestamp) when the poll will be automatically closed. Must be at least 5 and no more than 2628000 seconds in the future. Can't be used together with open_period. |
| is_closed | Boolean | Optional | Pass True if the poll needs to be immediately closed. This can be useful for poll preview. |
| description | String | Optional | Description of the poll to be sent, 0-1024 characters after entities parsing |
| description_parse_mode | String | Optional | Mode for parsing entities in the poll description. See formatting options for more details. |
| description_entities | Array of MessageEntity | Optional | A JSON-serialized list of special entities that appear in the poll description, which can be specified instead of description_parse_mode |
| media | InputPollMedia | Optional | Media added to the poll description |
| disable_notification | Boolean | Optional | Sends the message silently. Users will receive a notification with no sound. |
| protect_content | Boolean | Optional | Protects the contents of the sent message from forwarding and saving |
| allow_paid_broadcast | Boolean | Optional | Pass True to allow up to 1000 messages per second, ignoring broadcasting limits for a fee of 0.1 Telegram Stars per message. The relevant Stars will be withdrawn from the bot's balance. |
| message_effect_id | String | Optional | Unique identifier of the message effect to be added to the message; for private chats only |
| reply_parameters | ReplyParameters | Optional | Description of the message to reply to |
| reply_markup | InlineKeyboardMarkup or ReplyKeyboardMarkup or ReplyKeyboardRemove or ForceReply | Optional | Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove a reply keyboard or to force a reply from the user. |

#### Example

```php

```

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 12.148. sendrichmessage

> Use this method to send rich messages

Use this method to send rich messages. If the message contains a block with a media element, then the bot must have the right to send the media to the chat. On success, the sent Message is returned.

#### Parameters

| Parameter | Type | Required | Description |
| --- | --- | --- | --- |
| business_connection_id | String | Optional | Unique identifier of the business connection on behalf of which the message will be sent. Bot can send rich messages on behalf of a business account only if the corresponding user can send rich messages. |
| chat_id | Integer or String | Yes | Unique identifier for the target chat or username of the target bot, supergroup or channel in the format @username |
| message_thread_id | Integer | Optional | Unique identifier for the target message thread (topic) of a forum; for forum supergroups and private chats of bots with forum topic mode enabled only |
| direct_messages_topic_id | Integer | Optional | Identifier of the direct messages topic to which the message will be sent; required if the message is sent to a direct messages chat |
| ephemeral_message_parameters | EphemeralMessageParameters | Optional | A JSON-serialized object containing the parameters of the ephemeral message to send |
| rich_message | InputRichMessage | Yes | The message to be sent |
| disable_notification | Boolean | Optional | Sends the message silently. Users will receive a notification with no sound. |
| protect_content | Boolean | Optional | Protects the contents of the sent message from forwarding and saving |
| allow_paid_broadcast | Boolean | Optional | Pass True to allow up to 1000 messages per second, ignoring broadcasting limits for a fee of 0.1 Telegram Stars per message. The relevant Stars will be withdrawn from the bot's balance. |
| message_effect_id | String | Optional | Unique identifier of the message effect to be added to the message; for private chats only |
| suggested_post_parameters | SuggestedPostParameters | Optional | A JSON-serialized object containing the parameters of the suggested post to send; for direct messages chats only. If the message is sent as a reply to another suggested post, then that suggested post is automatically declined. |
| reply_parameters | ReplyParameters | Optional | Description of the message to reply to |
| reply_markup | InlineKeyboardMarkup or ReplyKeyboardMarkup or ReplyKeyboardRemove or ForceReply | Optional | Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove a reply keyboard or to force a reply from the user. |

#### Example

```php

```

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 12.149. sendrichmessagedraft

> Use this method to stream a partial rich message to a user while the message is being generated

Use this method to stream a partial rich message to a user while the message is being generated. Note that the streamed draft is ephemeral and acts as a temporary 30-second preview - once the output is finalized, you **must** call sendRichMessage with the complete message to persist it in the user's chat. Returns *True* on success.

#### Parameters

| Parameter | Type | Required | Description |
| --- | --- | --- | --- |
| chat_id | Integer | Yes | Unique identifier for the target private chat |
| message_thread_id | Integer | Optional | Unique identifier for the target message thread |
| draft_id | Integer | Yes | Unique identifier of the message draft; must be non-zero. Changes to drafts with the same identifier are animated. Otherwise, the draft is replaced without animation. |
| rich_message | InputRichMessage | Yes | The partial message to be streamed. Direct upload of new files and explicit upload of files by a URL isn't supported. |
| can_stop | Boolean | Optional | Pass True to show the user a button to stop further drafts. The bot will receive an Update "stopped_message_generation" if the user presses the button. |
| keep_on_stop | Boolean | Optional | Pass True to keep the draft in the chat when the button is pressed. The draft will still disappear after a short time or if the bot sends a message. To fully preserve the partial draft, the bot should send it as a new message. |

#### Example

```php

```

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 12.150. sendSticker

> Use this method to send static .WEBP, animated .TGS, or video .WEBM stickers

Use this method to send static .WEBP, animated .TGS, or video .WEBM stickers. On success, the sent Message is returned.

#### Parameters

| Parameter | Type | Required | Description |
| --- | --- | --- | --- |
| business_connection_id | String | Optional | Unique identifier of the business connection on behalf of which the message will be sent |
| chat_id | Integer or String | Yes | Unique identifier for the target chat or username of the target bot, supergroup or channel in the format @username |
| message_thread_id | Integer | Optional | Unique identifier for the target message thread (topic) of a forum; for forum supergroups and private chats of bots with forum topic mode enabled only |
| direct_messages_topic_id | Integer | Optional | Identifier of the direct messages topic to which the message will be sent; required if the message is sent to a direct messages chat |
| ephemeral_message_parameters | EphemeralMessageParameters | Optional | A JSON-serialized object containing the parameters of the ephemeral message to send |
| sticker | InputFile or String | Yes | Sticker to send. Pass a file_id as String to send a file that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a .WEBP sticker from the Internet, or upload a new .WEBP, .TGS, or .WEBM sticker using multipart/form-data. More information on Sending Files ». Video and animated stickers can't be sent via an HTTP URL. |
| emoji | String | Optional | Emoji associated with the sticker; only for just uploaded stickers |
| disable_notification | Boolean | Optional | Sends the message silently. Users will receive a notification with no sound. |
| protect_content | Boolean | Optional | Protects the contents of the sent message from forwarding and saving |
| allow_paid_broadcast | Boolean | Optional | Pass True to allow up to 1000 messages per second, ignoring broadcasting limits for a fee of 0.1 Telegram Stars per message. The relevant Stars will be withdrawn from the bot's balance. |
| message_effect_id | String | Optional | Unique identifier of the message effect to be added to the message; for private chats only |
| suggested_post_parameters | SuggestedPostParameters | Optional | A JSON-serialized object containing the parameters of the suggested post to send; for direct messages chats only. If the message is sent as a reply to another suggested post, then that suggested post is automatically declined. |
| reply_parameters | ReplyParameters | Optional | Description of the message to reply to |
| reply_markup | InlineKeyboardMarkup or ReplyKeyboardMarkup or ReplyKeyboardRemove or ForceReply | Optional | Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove a reply keyboard or to force a reply from the user. |

#### Example

```php

```

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 12.151. sendVenue

> Use this method to send information about a venue

Use this method to send information about a venue. On success, the sent Message is returned.

#### Parameters

| Parameter | Type | Required | Description |
| --- | --- | --- | --- |
| business_connection_id | String | Optional | Unique identifier of the business connection on behalf of which the message will be sent |
| chat_id | Integer or String | Yes | Unique identifier for the target chat or username of the target bot, supergroup or channel in the format @username |
| message_thread_id | Integer | Optional | Unique identifier for the target message thread (topic) of a forum; for forum supergroups and private chats of bots with forum topic mode enabled only |
| direct_messages_topic_id | Integer | Optional | Identifier of the direct messages topic to which the message will be sent; required if the message is sent to a direct messages chat |
| ephemeral_message_parameters | EphemeralMessageParameters | Optional | A JSON-serialized object containing the parameters of the ephemeral message to send |
| latitude | Float | Yes | Latitude of the venue |
| longitude | Float | Yes | Longitude of the venue |
| title | String | Yes | Name of the venue |
| address | String | Yes | Address of the venue |
| foursquare_id | String | Optional | Foursquare identifier of the venue |
| foursquare_type | String | Optional | Foursquare type of the venue, if known. (For example, "arts_entertainment/default", "arts_entertainment/aquarium" or "food/icecream".) |
| google_place_id | String | Optional | Google Places identifier of the venue |
| google_place_type | String | Optional | Google Places type of the venue. (See supported types.) |
| disable_notification | Boolean | Optional | Sends the message silently. Users will receive a notification with no sound. |
| protect_content | Boolean | Optional | Protects the contents of the sent message from forwarding and saving |
| allow_paid_broadcast | Boolean | Optional | Pass True to allow up to 1000 messages per second, ignoring broadcasting limits for a fee of 0.1 Telegram Stars per message. The relevant Stars will be withdrawn from the bot's balance. |
| message_effect_id | String | Optional | Unique identifier of the message effect to be added to the message; for private chats only |
| suggested_post_parameters | SuggestedPostParameters | Optional | A JSON-serialized object containing the parameters of the suggested post to send; for direct messages chats only. If the message is sent as a reply to another suggested post, then that suggested post is automatically declined. |
| reply_parameters | ReplyParameters | Optional | Description of the message to reply to |
| reply_markup | InlineKeyboardMarkup or ReplyKeyboardMarkup or ReplyKeyboardRemove or ForceReply | Optional | Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove a reply keyboard or to force a reply from the user. |

#### Example

```php

```

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 12.152. sendVideo

> Use this method to send video files, Telegram clients support MPEG4 videos (other formats may be sent as Document)

Use this method to send video files, Telegram clients support MPEG4 videos (other formats may be sent as Document). On success, the sent Message is returned. Bots can currently send video files of up to 50 MB in size, this limit may be changed in the future.

#### Parameters

| Parameter | Type | Required | Description |
| --- | --- | --- | --- |
| business_connection_id | String | Optional | Unique identifier of the business connection on behalf of which the message will be sent |
| chat_id | Integer or String | Yes | Unique identifier for the target chat or username of the target bot, supergroup or channel in the format @username |
| message_thread_id | Integer | Optional | Unique identifier for the target message thread (topic) of a forum; for forum supergroups and private chats of bots with forum topic mode enabled only |
| direct_messages_topic_id | Integer | Optional | Identifier of the direct messages topic to which the message will be sent; required if the message is sent to a direct messages chat |
| ephemeral_message_parameters | EphemeralMessageParameters | Optional | A JSON-serialized object containing the parameters of the ephemeral message to send |
| video | InputFile or String | Yes | Video to send. Pass a file_id as String to send a video that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a video from the Internet, or upload a new video using multipart/form-data. More information on Sending Files » |
| duration | Integer | Optional | Duration of sent video in seconds |
| width | Integer | Optional | Video width |
| height | Integer | Optional | Video height |
| thumbnail | InputFile or String | Optional | Thumbnail of the file sent; can be ignored if thumbnail generation for the file is supported server-side. The thumbnail should be in JPEG format and less than 200 kB in size. A thumbnail's width and height should not exceed 320. Ignored if the file is not uploaded using multipart/form-data. Thumbnails can't be reused and can be only uploaded as a new file, so you can pass "attach://<file_attach_name>" if the thumbnail was uploaded using multipart/form-data under <file_attach_name>. More information on Sending Files » |
| cover | InputFile or String | Optional | Cover for the video in the message. Pass a file_id to send a file that exists on the Telegram servers (recommended), pass an HTTP URL for Telegram to get a file from the Internet, or pass "attach://<file_attach_name>" to upload a new one using multipart/form-data under <file_attach_name> name. More information on Sending Files » |
| start_timestamp | Integer | Optional | Start timestamp for the video in the message |
| caption | String | Optional | Video caption (may also be used when resending videos by file_id), 0-1024 characters after entities parsing |
| parse_mode | String | Optional | Mode for parsing entities in the video caption. See formatting options for more details. |
| caption_entities | Array of MessageEntity | Optional | A JSON-serialized list of special entities that appear in the caption, which can be specified instead of parse_mode |
| show_caption_above_media | Boolean | Optional | Pass True if the caption must be shown above the message media |
| has_spoiler | Boolean | Optional | Pass True if the video needs to be covered with a spoiler animation |
| supports_streaming | Boolean | Optional | Pass True if the uploaded video is suitable for streaming |
| disable_notification | Boolean | Optional | Sends the message silently. Users will receive a notification with no sound. |
| protect_content | Boolean | Optional | Protects the contents of the sent message from forwarding and saving |
| allow_paid_broadcast | Boolean | Optional | Pass True to allow up to 1000 messages per second, ignoring broadcasting limits for a fee of 0.1 Telegram Stars per message. The relevant Stars will be withdrawn from the bot's balance. |
| message_effect_id | String | Optional | Unique identifier of the message effect to be added to the message; for private chats only |
| suggested_post_parameters | SuggestedPostParameters | Optional | A JSON-serialized object containing the parameters of the suggested post to send; for direct messages chats only. If the message is sent as a reply to another suggested post, then that suggested post is automatically declined. |
| reply_parameters | ReplyParameters | Optional | Description of the message to reply to |
| reply_markup | InlineKeyboardMarkup or ReplyKeyboardMarkup or ReplyKeyboardRemove or ForceReply | Optional | Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove a reply keyboard or to force a reply from the user. |

#### Example

```php

```

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 12.153. sendVideoNote

> Use this method to send a rounded square MPEG4 video of up to 1 minute long

Use this method to send a rounded square MPEG4 video of up to 1 minute long. On success, the sent Message is returned.

#### Parameters

| Parameter | Type | Required | Description |
| --- | --- | --- | --- |
| business_connection_id | String | Optional | Unique identifier of the business connection on behalf of which the message will be sent |
| chat_id | Integer or String | Yes | Unique identifier for the target chat or username of the target bot, supergroup or channel in the format @username |
| message_thread_id | Integer | Optional | Unique identifier for the target message thread (topic) of a forum; for forum supergroups and private chats of bots with forum topic mode enabled only |
| direct_messages_topic_id | Integer | Optional | Identifier of the direct messages topic to which the message will be sent; required if the message is sent to a direct messages chat |
| ephemeral_message_parameters | EphemeralMessageParameters | Optional | A JSON-serialized object containing the parameters of the ephemeral message to send |
| video_note | InputFile or String | Yes | Video note to send. Pass a file_id as String to send a video note that exists on the Telegram servers (recommended) or upload a new video using multipart/form-data. More information on Sending Files ». Sending video notes by a URL is currently unsupported. |
| duration | Integer | Optional | Duration of sent video in seconds |
| length | Integer | Optional | Video width and height, i.e. diameter of the video message |
| thumbnail | InputFile or String | Optional | Thumbnail of the file sent; can be ignored if thumbnail generation for the file is supported server-side. The thumbnail should be in JPEG format and less than 200 kB in size. A thumbnail's width and height should not exceed 320. Ignored if the file is not uploaded using multipart/form-data. Thumbnails can't be reused and can be only uploaded as a new file, so you can pass "attach://<file_attach_name>" if the thumbnail was uploaded using multipart/form-data under <file_attach_name>. More information on Sending Files » |
| disable_notification | Boolean | Optional | Sends the message silently. Users will receive a notification with no sound. |
| protect_content | Boolean | Optional | Protects the contents of the sent message from forwarding and saving |
| allow_paid_broadcast | Boolean | Optional | Pass True to allow up to 1000 messages per second, ignoring broadcasting limits for a fee of 0.1 Telegram Stars per message. The relevant Stars will be withdrawn from the bot's balance. |
| message_effect_id | String | Optional | Unique identifier of the message effect to be added to the message; for private chats only |
| suggested_post_parameters | SuggestedPostParameters | Optional | A JSON-serialized object containing the parameters of the suggested post to send; for direct messages chats only. If the message is sent as a reply to another suggested post, then that suggested post is automatically declined. |
| reply_parameters | ReplyParameters | Optional | Description of the message to reply to |
| reply_markup | InlineKeyboardMarkup or ReplyKeyboardMarkup or ReplyKeyboardRemove or ForceReply | Optional | Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove a reply keyboard or to force a reply from the user. |

#### Example

```php

```

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 12.154. sendVoice

> Use this method to send audio files, if you want Telegram clients to display the file as a playable voice message

Use this method to send audio files, if you want Telegram clients to display the file as a playable voice message. For this to work, your audio must be in an .OGG file encoded with OPUS, or in .MP3 format, or in .M4A format (other formats may be sent as Audio or Document). On success, the sent Message is returned. Bots can currently send voice messages of up to 50 MB in size, this limit may be changed in the future.

#### Parameters

| Parameter | Type | Required | Description |
| --- | --- | --- | --- |
| business_connection_id | String | Optional | Unique identifier of the business connection on behalf of which the message will be sent |
| chat_id | Integer or String | Yes | Unique identifier for the target chat or username of the target bot, supergroup or channel in the format @username |
| message_thread_id | Integer | Optional | Unique identifier for the target message thread (topic) of a forum; for forum supergroups and private chats of bots with forum topic mode enabled only |
| direct_messages_topic_id | Integer | Optional | Identifier of the direct messages topic to which the message will be sent; required if the message is sent to a direct messages chat |
| ephemeral_message_parameters | EphemeralMessageParameters | Optional | A JSON-serialized object containing the parameters of the ephemeral message to send |
| voice | InputFile or String | Yes | Audio file to send. Pass a file_id as String to send a file that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a file from the Internet, or upload a new one using multipart/form-data. More information on Sending Files » |
| caption | String | Optional | Voice message caption, 0-1024 characters after entities parsing |
| parse_mode | String | Optional | Mode for parsing entities in the voice message caption. See formatting options for more details. |
| caption_entities | Array of MessageEntity | Optional | A JSON-serialized list of special entities that appear in the caption, which can be specified instead of parse_mode |
| duration | Integer | Optional | Duration of the voice message in seconds |
| disable_notification | Boolean | Optional | Sends the message silently. Users will receive a notification with no sound. |
| protect_content | Boolean | Optional | Protects the contents of the sent message from forwarding and saving |
| allow_paid_broadcast | Boolean | Optional | Pass True to allow up to 1000 messages per second, ignoring broadcasting limits for a fee of 0.1 Telegram Stars per message. The relevant Stars will be withdrawn from the bot's balance. |
| message_effect_id | String | Optional | Unique identifier of the message effect to be added to the message; for private chats only |
| suggested_post_parameters | SuggestedPostParameters | Optional | A JSON-serialized object containing the parameters of the suggested post to send; for direct messages chats only. If the message is sent as a reply to another suggested post, then that suggested post is automatically declined. |
| reply_parameters | ReplyParameters | Optional | Description of the message to reply to |
| reply_markup | InlineKeyboardMarkup or ReplyKeyboardMarkup or ReplyKeyboardRemove or ForceReply | Optional | Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove a reply keyboard or to force a reply from the user. |

#### Example

```php

```

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 12.155. setBusinessAccountBio

> Changes the bio of a managed business account

Changes the bio of a managed business account. Requires the *can_change_bio* business bot right. Returns *True* on success.

#### Parameters

| Parameter | Type | Required | Description |
| --- | --- | --- | --- |
| business_connection_id | String | Yes | Unique identifier of the business connection |
| bio | String | Optional | The new value of the bio for the business account; 0-140 characters |

#### Example

```php

```

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 12.156. setBusinessAccountGiftSettings

> Changes the privacy settings pertaining to incoming gifts in a managed business account

Changes the privacy settings pertaining to incoming gifts in a managed business account. Requires the *can_change_gift_settings* business bot right. Returns *True* on success.

#### Parameters

| Parameter | Type | Required | Description |
| --- | --- | --- | --- |
| business_connection_id | String | Yes | Unique identifier of the business connection |
| show_gift_button | Boolean | Yes | Pass True if a button for sending a gift to the user or by the business account must always be shown in the input field |
| accepted_gift_types | AcceptedGiftTypes | Yes | Types of gifts accepted by the business account |

#### Example

```php

```

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 12.157. setBusinessAccountName

> Changes the first and last name of a managed business account

Changes the first and last name of a managed business account. Requires the *can_change_name* business bot right. Returns *True* on success.

#### Parameters

| Parameter | Type | Required | Description |
| --- | --- | --- | --- |
| business_connection_id | String | Yes | Unique identifier of the business connection |
| first_name | String | Yes | The new value of the first name for the business account; 1-64 characters |
| last_name | String | Optional | The new value of the last name for the business account; 0-64 characters |

#### Example

```php

```

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 12.158. setBusinessAccountProfilePhoto

> Changes the profile photo of a managed business account

Changes the profile photo of a managed business account. Requires the *can_edit_profile_photo* business bot right. Returns *True* on success.

#### Parameters

| Parameter | Type | Required | Description |
| --- | --- | --- | --- |
| business_connection_id | String | Yes | Unique identifier of the business connection |
| photo | InputProfilePhoto | Yes | The new profile photo to set |
| is_public | Boolean | Optional | Pass True to set the public photo, which will be visible even if the main photo is hidden by the business account's privacy settings. An account can have only one public photo. |

#### Example

```php

```

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 12.159. setBusinessAccountUsername

> Changes the username of a managed business account

Changes the username of a managed business account. Requires the *can_change_username* business bot right. Returns *True* on success.

#### Parameters

| Parameter | Type | Required | Description |
| --- | --- | --- | --- |
| business_connection_id | String | Yes | Unique identifier of the business connection |
| username | String | Optional | The new value of the username for the business account; 0-32 characters |

#### Example

```php

```

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 12.160. setChatAdministratorCustomTitle

> Use this method to set a custom title for an administrator in a supergroup promoted by the bot

Use this method to set a custom title for an administrator in a supergroup promoted by the bot. Returns *True* on success.

#### Parameters

| Parameter | Type | Required | Description |
| --- | --- | --- | --- |
| chat_id | Integer or String | Yes | Unique identifier for the target chat or username of the target supergroup in the format @username |
| user_id | Integer | Yes | Unique identifier of the target user |
| custom_title | String | Yes | New custom title for the administrator; 0-16 characters, emoji are not allowed |

#### Example

```php

```

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 12.161. setChatDescription

> Use this method to change the description of a group, a supergroup or a channel

Use this method to change the description of a group, a supergroup or a channel. The bot must be an administrator in the chat for this to work and must have the appropriate administrator rights. Returns *True* on success.

#### Parameters

| Parameter | Type | Required | Description |
| --- | --- | --- | --- |
| chat_id | Integer or String | Yes | Unique identifier for the target chat or username of the target channel in the format @username |
| description | String | Optional | New chat description, 0-255 characters |

#### Example

```php

```

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 12.162. setChatMemberTag

> Use this method to set a tag for a regular member in a group or a supergroup

Use this method to set a tag for a regular member in a group or a supergroup. The bot must be an administrator in the chat for this to work and must have the *can_manage_tags* administrator right. Returns *True* on success.

#### Parameters

| Parameter | Type | Required | Description |
| --- | --- | --- | --- |
| chat_id | Integer or String | Yes | Unique identifier for the target chat or username of the target supergroup in the format @username |
| user_id | Integer | Yes | Unique identifier of the target user |
| tag | String | Optional | New tag for the member; 0-16 characters, emoji are not allowed |

#### Example

```php

```

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 12.163. setChatMenuButton

> Use this method to change the bot's menu button in a private chat, or the default menu button

Use this method to change the bot's menu button in a private chat, or the default menu button. Returns *True* on success.

#### Parameters

| Parameter | Type | Required | Description |
| --- | --- | --- | --- |
| chat_id | Integer | Optional | Unique identifier for the target private chat. If not specified, the bot's default menu button will be changed. |
| menu_button | MenuButton | Optional | A JSON-serialized object for the bot's new menu button. Defaults to MenuButtonDefault. |

#### Example

```php

```

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 12.164. setChatPermissions

> Use this method to set default chat permissions for all members

Use this method to set default chat permissions for all members. The bot must be an administrator in the group or a supergroup for this to work and must have the *can_restrict_members* administrator rights. Returns *True* on success.

#### Parameters

| Parameter | Type | Required | Description |
| --- | --- | --- | --- |
| chat_id | Integer or String | Yes | Unique identifier for the target chat or username of the target supergroup in the format @username |
| permissions | ChatPermissions | Yes | A JSON-serialized object for new default chat permissions |
| use_independent_chat_permissions | Boolean | Optional | Pass True if chat permissions are set independently. Otherwise, the can_send_other_messages and can_add_web_page_previews permissions will imply the can_send_messages, can_send_audios, can_send_documents, can_send_photos, can_send_videos, can_send_video_notes, and can_send_voice_notes permissions; the can_send_polls permission will imply the can_send_messages permission. |

#### Example

```php

```

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 12.165. setChatPhoto

> Use this method to set a new profile photo for the chat

Use this method to set a new profile photo for the chat. Photos can't be changed for private chats. The bot must be an administrator in the chat for this to work and must have the appropriate administrator rights. Returns *True* on success.

#### Parameters

| Parameter | Type | Required | Description |
| --- | --- | --- | --- |
| chat_id | Integer or String | Yes | Unique identifier for the target chat or username of the target channel in the format @username |
| photo | InputFile | Yes | New chat photo, uploaded using multipart/form-data |

#### Example

```php

```

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 12.166. setChatStickerSet

> Use this method to set a new group sticker set for a supergroup

Use this method to set a new group sticker set for a supergroup. The bot must be an administrator in the chat for this to work and must have the appropriate administrator rights. Use the field *can_set_sticker_set* optionally returned in getChat requests to check if the bot can use this method. Returns *True* on success.

#### Parameters

| Parameter | Type | Required | Description |
| --- | --- | --- | --- |
| chat_id | Integer or String | Yes | Unique identifier for the target chat or username of the target supergroup in the format @username |
| sticker_set_name | String | Yes | Name of the sticker set to be set as the group sticker set |

#### Example

```php

```

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 12.167. setChatTitle

> Use this method to change the title of a chat

Use this method to change the title of a chat. Titles can't be changed for private chats. The bot must be an administrator in the chat for this to work and must have the appropriate administrator rights. Returns *True* on success.

#### Parameters

| Parameter | Type | Required | Description |
| --- | --- | --- | --- |
| chat_id | Integer or String | Yes | Unique identifier for the target chat or username of the target channel in the format @username |
| title | String | Yes | New chat title, 1-128 characters |

#### Example

```php

```

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 12.168. setCustomEmojiStickerSetThumbnail

> Use this method to set the thumbnail of a custom emoji sticker set

Use this method to set the thumbnail of a custom emoji sticker set. Returns *True* on success.

#### Parameters

| Parameter | Type | Required | Description |
| --- | --- | --- | --- |
| name | String | Yes | Sticker set name |
| custom_emoji_id | String | Optional | Custom emoji identifier of a sticker from the sticker set; pass an empty string to drop the thumbnail and use the first sticker as the thumbnail |

#### Example

```php

```

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 12.169. setGameScore

> Use this method to set the score of the specified user in a game message

Use this method to set the score of the specified user in a game message. On success, if the message is not an inline message, the Message is returned, otherwise *True* is returned. Returns an error, if the new score is not greater than the user's current score in the chat and *force* is *False*.

#### Parameters

| Parameter | Type | Required | Description |
| --- | --- | --- | --- |
| user_id | Integer | Yes | User identifier |
| score | Integer | Yes | New score, must be non-negative |
| force | Boolean | Optional | Pass True if the high score is allowed to decrease. This can be useful when fixing mistakes or banning cheaters. |
| disable_edit_message | Boolean | Optional | Pass True if the game message should not be automatically edited to include the current scoreboard |
| chat_id | Integer | Optional | Required if inline_message_id is not specified. Unique identifier for the target chat. |
| message_id | Integer | Optional | Required if inline_message_id is not specified. Identifier of the sent message. |
| inline_message_id | String | Optional | Required if chat_id and message_id are not specified. Identifier of the inline message. |

#### Example

```php

```

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 12.170. setManagedBotAccessSettings

> Use this method to change the access settings of a managed bot

Use this method to change the access settings of a managed bot. Returns *True* on success.

#### Parameters

| Parameter | Type | Required | Description |
| --- | --- | --- | --- |
| user_id | Integer | Yes | User identifier of the managed bot whose access settings will be changed |
| is_access_restricted | Boolean | Yes | Pass True if only selected users can access the bot. The bot's owner can always access it. |
| added_user_ids | Array of Integer | Optional | A JSON-serialized list of up to 10 identifiers of users who will have access to the bot in addition to its owner. Ignored if is_access_restricted is False. |

#### Example

```php

```

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 12.171. setMessageReaction

> Use this method to change the chosen reactions on a message

Use this method to change the chosen reactions on a message. Service messages of some types can't be reacted to. Automatically forwarded messages from a channel to its discussion group have the same available reactions as messages in the channel. Bots can't use paid reactions. Returns *True* on success.

#### Parameters

| Parameter | Type | Required | Description |
| --- | --- | --- | --- |
| chat_id | Integer or String | Yes | Unique identifier for the target chat or username of the target bot, supergroup or channel in the format @username |
| message_id | Integer | Yes | Identifier of the target message. If the message belongs to a media group, the reaction is set to the first non-deleted message in the group instead. |
| reaction | Array of ReactionType | Optional | A JSON-serialized list of reaction types to set on the message. Currently, as non-premium users, bots can set up to one reaction per message. A custom emoji reaction can be used if it is either already present on the message or explicitly allowed by chat administrators. Paid reactions can't be used by bots. |
| is_big | Boolean | Optional | Pass True to set the reaction with a big animation |

#### Example

```php

```

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 12.172. setMyCommands

> Use this method to change the list of the bot's commands

Use this method to change the list of the bot's commands. See this manual for more details about bot commands. Returns *True* on success.

#### Parameters

| Parameter | Type | Required | Description |
| --- | --- | --- | --- |
| commands | Array of BotCommand | Yes | A JSON-serialized list of bot commands to be set as the list of the bot's commands. At most 100 commands can be specified. |
| scope | BotCommandScope | Optional | A JSON-serialized object, describing scope of users for which the commands are relevant. Defaults to BotCommandScopeDefault. |
| language_code | String | Optional | A two-letter ISO 639-1 language code. If empty, commands will be applied to all users from the given scope, for whose language there are no dedicated commands. |

#### Example

```php

```

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 12.173. setMyDefaultAdministratorRights

> Use this method to change the default administrator rights requested by the bot when it's added as an administrator to groups or channels

Use this method to change the default administrator rights requested by the bot when it's added as an administrator to groups or channels. These rights will be suggested to users, but they are free to modify the list before adding the bot. Returns *True* on success.

#### Parameters

| Parameter | Type | Required | Description |
| --- | --- | --- | --- |
| rights | ChatAdministratorRights | Optional | A JSON-serialized object describing new default administrator rights. If not specified, the default administrator rights will be cleared. |
| for_channels | Boolean | Optional | Pass True to change the default administrator rights of the bot in channels. Otherwise, the default administrator rights of the bot for groups and supergroups will be changed. |

#### Example

```php

```

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 12.174. setMyDescription

> Use this method to change the bot's description, which is shown in the chat with the bot if the chat is empty

Use this method to change the bot's description, which is shown in the chat with the bot if the chat is empty. Returns *True* on success.

#### Parameters

| Parameter | Type | Required | Description |
| --- | --- | --- | --- |
| description | String | Optional | New bot description; 0-512 characters. Pass an empty string to remove the dedicated description for the given language. |
| language_code | String | Optional | A two-letter ISO 639-1 language code. If empty, the description will be applied to all users for whose language there is no dedicated description. |

#### Example

```php

```

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 12.175. setMyName

> Use this method to change the bot's name

Use this method to change the bot's name. Returns *True* on success.

#### Parameters

| Parameter | Type | Required | Description |
| --- | --- | --- | --- |
| name | String | Optional | New bot name; 0-64 characters. Pass an empty string to remove the dedicated name for the given language. |
| language_code | String | Optional | A two-letter ISO 639-1 language code. If empty, the name will be shown to all users for whose language there is no dedicated name. |

#### Example

```php

```

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 12.176. setMyProfilePhoto

> Changes the profile photo of the bot

Changes the profile photo of the bot. Returns *True* on success.

#### Parameters

| Parameter | Type | Required | Description |
| --- | --- | --- | --- |
| photo | InputProfilePhoto | Yes | The new profile photo to set |

#### Example

```php

```

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 12.177. setMyShortDescription

> Use this method to change the bot's short description, which is shown on the bot's profile page and is sent together with the link when user

Use this method to change the bot's short description, which is shown on the bot's profile page and is sent together with the link when users share the bot. Returns *True* on success.

#### Parameters

| Parameter | Type | Required | Description |
| --- | --- | --- | --- |
| short_description | String | Optional | New short description for the bot; 0-120 characters. Pass an empty string to remove the dedicated short description for the given language. |
| language_code | String | Optional | A two-letter ISO 639-1 language code. If empty, the short description will be applied to all users for whose language there is no dedicated short description. |

#### Example

```php

```

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 12.178. setPassportDataErrors

> Informs a user that some of the Telegram Passport elements they provided contains errors

Informs a user that some of the Telegram Passport elements they provided contains errors. The user will not be able to re-submit their Passport to you until the errors are fixed (the contents of the field for which you returned the error must change). Returns *True* on success.

Use this if the data submitted by the user doesn't satisfy the standards your service requires for any reason. For example, if a birthday date seems invalid, a submitted document is blurry, a scan shows evidence of tampering, etc. Supply some details in the error message to make sure the user knows how to correct the issues.

#### Parameters

| Parameter | Type | Required | Description |
| --- | --- | --- | --- |
| user_id | Integer | Yes | User identifier |
| errors | Array of PassportElementError | Yes | A JSON-serialized Array describing the errors |

#### Example

```php

```

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 12.179. setStickerEmojiList

> Use this method to change the list of emoji assigned to a regular or custom emoji sticker

Use this method to change the list of emoji assigned to a regular or custom emoji sticker. The sticker must belong to a sticker set created by the bot. Returns *True* on success.

#### Parameters

| Parameter | Type | Required | Description |
| --- | --- | --- | --- |
| sticker | String | Yes | File identifier of the sticker |
| emoji_list | Array of String | Yes | A JSON-serialized list of 1-20 emoji associated with the sticker |

#### Example

```php

```

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 12.180. setStickerKeywords

> Use this method to change search keywords assigned to a regular or custom emoji sticker

Use this method to change search keywords assigned to a regular or custom emoji sticker. The sticker must belong to a sticker set created by the bot. Returns *True* on success.

#### Parameters

| Parameter | Type | Required | Description |
| --- | --- | --- | --- |
| sticker | String | Yes | File identifier of the sticker |
| keywords | Array of String | Optional | A JSON-serialized list of 0-20 search keywords for the sticker with total length of up to 64 characters |

#### Example

```php

```

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 12.181. setStickerMaskPosition

> Use this method to change the mask position of a mask sticker

Use this method to change the mask position of a mask sticker. The sticker must belong to a sticker set that was created by the bot. Returns *True* on success.

#### Parameters

| Parameter | Type | Required | Description |
| --- | --- | --- | --- |
| sticker | String | Yes | File identifier of the sticker |
| mask_position | MaskPosition | Optional | A JSON-serialized object with the position where the mask should be placed on faces. Omit the parameter to remove the mask position. |

#### Example

```php

```

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 12.182. setStickerPositionInSet

> Use this method to move a sticker in a set created by the bot to a specific position

Use this method to move a sticker in a set created by the bot to a specific position. Returns *True* on success.

#### Parameters

| Parameter | Type | Required | Description |
| --- | --- | --- | --- |
| sticker | String | Yes | File identifier of the sticker |
| position | Integer | Yes | New sticker position in the set, zero-based |

#### Example

```php

```

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 12.183. setStickerSetThumbnail

> Use this method to set the thumbnail of a regular or mask sticker set

Use this method to set the thumbnail of a regular or mask sticker set. The format of the thumbnail file must match the format of the stickers in the set. Returns *True* on success.

#### Parameters

| Parameter | Type | Required | Description |
| --- | --- | --- | --- |
| name | String | Yes | Sticker set name |
| user_id | Integer | Yes | User identifier of the sticker set owner |
| thumbnail | InputFile or String | Optional | A .WEBP or .PNG image with the thumbnail, must be up to 128 kilobytes in size and have a width and height of exactly 100px, or a .TGS animation with a thumbnail up to 32 kilobytes in size (see https://core.telegram.org/stickers#animation-requirements for animated sticker technical requirements), or a .WEBM video with the thumbnail up to 32 kilobytes in size; see https://core.telegram.org/stickers#video-requirements for video sticker technical requirements. Pass a file_id as a String to send a file that already exists on the Telegram servers, pass an HTTP URL as a String for Telegram to get a file from the Internet, or upload a new one using multipart/form-data. More information on Sending Files ». Animated and video sticker set thumbnails can't be uploaded via HTTP URL. If omitted, then the thumbnail is dropped and the first sticker is used as the thumbnail. |
| format | String | Yes | Format of the thumbnail, must be one of "static" for a .WEBP or .PNG image, "animated" for a .TGS animation, or "video" for a .WEBM video |

#### Example

```php

```

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 12.184. setStickerSetTitle

> Use this method to set the title of a created sticker set

Use this method to set the title of a created sticker set. Returns *True* on success.

#### Parameters

| Parameter | Type | Required | Description |
| --- | --- | --- | --- |
| name | String | Yes | Sticker set name |
| title | String | Yes | Sticker set title, 1-64 characters |

#### Example

```php

```

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 12.185. setUserEmojiStatus

> Changes the emoji status for a given user that previously allowed the bot to manage their emoji status via the Mini App method requestEmojiS

Changes the emoji status for a given user that previously allowed the bot to manage their emoji status via the Mini App method requestEmojiStatusAccess. Returns *True* on success.

#### Parameters

| Parameter | Type | Required | Description |
| --- | --- | --- | --- |
| user_id | Integer | Yes | Unique identifier of the target user |
| emoji_status_custom_emoji_id | String | Optional | Custom emoji identifier of the emoji status to set. Pass an empty string to remove the status. |
| emoji_status_expiration_date | Integer | Optional | Expiration date of the emoji status, if any |

#### Example

```php

```

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 12.186. setWebhook

> Use this method to specify a URL and receive incoming updates via an outgoing webhook

Use this method to specify a URL and receive incoming updates via an outgoing webhook. Whenever there is an update for the bot, we will send an HTTPS POST request to the specified URL, containing a JSON-serialized Update. In case of an unsuccessful request (a request with response HTTP status code different from `2XY`), we will repeat the request and give up after a reasonable amount of attempts. Returns *True* on success.

If you'd like to make sure that the webhook was set by you, you can specify secret data in the parameter *secret_token*. If specified, the request will contain a header "X-Telegram-Bot-Api-Secret-Token" with the secret token as content.

Please note that this parameter doesn't affect updates created before the call to the setWebhook, so unwanted updates may be received for a short period of time.

**1.** You will not be able to receive updates using getUpdates for as long as an outgoing webhook is set up.

**2.** To use a self-signed certificate, you need to upload your public key certificate using *certificate* parameter. Please upload as InputFile, sending a String will not work.

**3.** Ports currently supported *for webhooks*: **443, 80, 88, 8443**.

#### Parameters

| Parameter | Type | Required | Description |
| --- | --- | --- | --- |
| url | String | Yes | HTTPS URL to send updates to. Use an empty string to remove webhook integration. |
| certificate | InputFile | Optional | Upload your public key certificate so that the root certificate in use can be checked. See our self-signed guide for details. |
| ip_address | String | Optional | The fixed IP address which will be used to send webhook requests instead of the IP address resolved through DNS |
| max_connections | Integer | Optional | The maximum allowed number of simultaneous HTTPS connections to the webhook for update delivery, 1-100. Defaults to 40. Use lower values to limit the load on your bot's server, and higher values to increase your bot's throughput. |
| allowed_updates | Array of String | Optional | A JSON-serialized list of the update types you want your bot to receive. For example, specify ["message", "edited_channel_post", "callback_query"] to only receive updates of these types. See Update for a complete list of available update types. Specify an empty list to receive all update types except chat_member, message_reaction, and message_reaction_count (default). If not specified, the previous setting will be used. |

#### Example

```php

```

> [!NOTE]
> **Official Notes**
> Notes If you're having any trouble setting up webhooks, please check out this amazing guide to webhooks.

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 12.187. stopMessageLiveLocation

> Use this method to stop updating a live location message before *live_period* expires

Use this method to stop updating a live location message before *live_period* expires. On success, if the message is not an inline message, the edited Message is returned, otherwise *True* is returned.

#### Parameters

| Parameter | Type | Required | Description |
| --- | --- | --- | --- |
| business_connection_id | String | Optional | Unique identifier of the business connection on behalf of which the message to be edited was sent |
| chat_id | Integer or String | Optional | Required if inline_message_id is not specified. Unique identifier for the target chat or username of the target bot, supergroup or channel in the format @username. |
| message_id | Integer | Optional | Required if inline_message_id is not specified. Identifier of the message with live location to stop. |
| inline_message_id | String | Optional | Required if chat_id and message_id are not specified. Identifier of the inline message. |
| reply_markup | InlineKeyboardMarkup | Optional | A JSON-serialized object for a new inline keyboard |

#### Example

```php

```

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 12.188. stopPoll

> Use this method to stop a poll which was sent by the bot

Use this method to stop a poll which was sent by the bot. On success, the stopped Poll is returned.

#### Parameters

| Parameter | Type | Required | Description |
| --- | --- | --- | --- |
| business_connection_id | String | Optional | Unique identifier of the business connection on behalf of which the message to be edited was sent |
| chat_id | Integer or String | Yes | Unique identifier for the target chat or username of the target bot, supergroup or channel in the format @username |
| message_id | Integer | Yes | Identifier of the original message with the poll |
| reply_markup | InlineKeyboardMarkup | Optional | A JSON-serialized object for a new message inline keyboard |

#### Example

```php

```

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 12.189. Telegram Mini Apps (TMA), Fullscreen & initData Validation

> Launch full-screen Web Apps, validate initData cryptographically with HMAC-SHA256 in PHP 8.2, and dispatch prepared inline messages.

#### Telegram Mini Apps (TMA) Architecture

   

**Telegram Mini Apps** allow you to embed modern HTML5/JavaScript web applications directly inside Telegram. Mini Apps support full-screen mode, native dark/light theme synchronization, haptic feedback, cloud storage, biometric authentication, and Telegram Stars checkout.

   

#### 1. Launching Mini Apps from Buttons

   

Mini Apps can be opened from Inline Keyboards, Reply Keyboards, or the persistent Chat Menu Button:

   
```php

```

   

#### 2. Cryptographic initData Validation in Pure PHP 8.2

   

When a user opens your Mini App, Telegram injects a secure string called `initData` containing the user's ID, name, username, and a cryptographic `hash`. To prevent attackers from spoofing identities, you **MUST validate this hash on your PHP backend** using your `BOT_TOKEN`:

   
```php

```

   

#### 3. Full-Screen Mode & Orientation Locks (API 8.0)

   

Inside your Mini App's front-end JavaScript, you can request full-screen mode and lock screen orientation:

   
```php
// Check if Telegram WebApp SDK is available
if (window.Telegram?.WebApp) {
    const tg = window.Telegram.WebApp;
    tg.ready();

    // 1. Expand to maximum height
    tg.expand();

    // 2. Request True Full-Screen Mode (Telegram 8.0+)
    if (tg.requestFullscreen) {
        tg.requestFullscreen();
    }

    // 3. Lock Orientation to Landscape (Great for Web3 games)
    if (tg.lockOrientation) {
        tg.lockOrientation('landscape');
    }

    // 4. Disable Vertical Swipes (Prevents accidental sheet closing)
    if (tg.disableVerticalSwipes) {
        tg.disableVerticalSwipes();
    }
}
```

   

#### 4. Prepared Inline Messages (savePreparedInlineMessage)

   

Mini Apps can pre-package rich interactive messages on the server so users can share them into any Telegram chat with one tap:

   
```php

```

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 12.190. transferBusinessAccountStars

> Transfers Telegram Stars from the business account balance to the bot's balance

Transfers Telegram Stars from the business account balance to the bot's balance. Requires the *can_transfer_stars* business bot right. Returns *True* on success.

#### Parameters

| Parameter | Type | Required | Description |
| --- | --- | --- | --- |
| business_connection_id | String | Yes | Unique identifier of the business connection |
| star_count | Integer | Yes | Number of Telegram Stars to transfer; 1-10000 |

#### Example

```php

```

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 12.191. transferGift

> Transfers an owned unique gift to another user

Transfers an owned unique gift to another user. Requires the *can_transfer_and_upgrade_gifts* business bot right. Requires *can_transfer_stars* business bot right if the transfer is paid. Returns *True* on success.

#### Parameters

| Parameter | Type | Required | Description |
| --- | --- | --- | --- |
| business_connection_id | String | Yes | Unique identifier of the business connection |
| owned_gift_id | String | Yes | Unique identifier of the regular gift that should be transferred |
| new_owner_chat_id | Integer | Yes | Unique identifier of the chat which will own the gift. The chat must be active in the last 24 hours. |
| star_count | Integer | Optional | The amount of Telegram Stars that will be paid for the transfer from the business account balance. If positive, then the can_transfer_stars business bot right is required. |

#### Example

```php

```

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 12.192. unbanChatMember

> Use this method to unban a previously banned user in a supergroup or channel

Use this method to unban a previously banned user in a supergroup or channel. The user will **not** return to the group or channel automatically, but will be able to join via link, etc. The bot must be an administrator for this to work. By default, this method guarantees that after the call the user is not a member of the chat, but will be able to join it. So if the user is a member of the chat they will also be **removed** from the chat. If you don't want this, use the parameter *only_if_banned*. Returns *True* on success.

#### Parameters

| Parameter | Type | Required | Description |
| --- | --- | --- | --- |
| chat_id | Integer or String | Yes | Unique identifier for the target group or username of the target supergroup or channel in the format @username |
| user_id | Integer | Yes | Unique identifier of the target user |
| only_if_banned | Boolean | Optional | Do nothing if the user is not banned |

#### Example

```php

```

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 12.193. unbanChatSenderChat

> Use this method to unban a previously banned channel chat in a supergroup or channel

Use this method to unban a previously banned channel chat in a supergroup or channel. The bot must be an administrator for this to work and must have the appropriate administrator rights. Returns *True* on success.

#### Parameters

| Parameter | Type | Required | Description |
| --- | --- | --- | --- |
| chat_id | Integer or String | Yes | Unique identifier for the target chat or username of the target channel in the format @username |
| sender_chat_id | Integer | Yes | Unique identifier of the target sender chat |

#### Example

```php

```

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 12.194. unhideGeneralForumTopic

> Use this method to unhide the 'General' topic in a forum supergroup chat

Use this method to unhide the 'General' topic in a forum supergroup chat. The bot must be an administrator in the chat for this to work and must have the *can_manage_topics* administrator rights. Returns *True* on success.

#### Parameters

| Parameter | Type | Required | Description |
| --- | --- | --- | --- |
| chat_id | Integer or String | Yes | Unique identifier for the target chat or username of the target supergroup in the format @username |

#### Example

```php

```

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 12.195. Universal Multi-Media Broadcast Engine (copyMessage)

> Deliver text, photos, videos, voice notes, stickers, and channel forwards to all users with safe rate-limited pacing.

#### Universal Multi-Media Broadcast System

   

Mass announcements and notifications are essential for audience engagement. Botlify Cloud standardizes multi-media broadcasting using Telegram's official `copyMessage` API method, enabling administrators to broadcast any rich content type without uploading files multiple times.

   

#### Why copyMessage Outperforms sendMessage

   
| Feature | Traditional sendMessage | Botlify copyMessage Engine |
| --- | --- | --- |
| Supported Content | Plain text / HTML only | Text, Photo, Video, Document, Voice, Audio, Sticker, GIF, Channel Forwards |
| Media Upload Overhead | Re-uploads media on every call | Clones message on Telegram's servers (Zero Bandwidth) |
| Formatting Preservation | Requires manual parse_mode tag parsing | Preserves original captions, spoiler tags, and entities automatically |

   

#### Production Implementation Pattern

   

The following engine pattern is recommended for all production bots on Botlify Cloud:

      
```php

```

   
> [!TIP]
> **Safe Anti-Flood Pacing (38ms Sleep)**
> Telegram enforces an outbound limit of approximately 30 messages per second per bot. Pausing execution for usleep(38000) (~38 milliseconds) caps delivery at ~26 messages per second, ensuring smooth delivery without triggering HTTP 429 Too Many Requests or account throttling.

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 12.196. unpinAllChatMessages

> Use this method to clear the list of pinned messages in a chat

Use this method to clear the list of pinned messages in a chat. In private chats and channel direct messages chats, no additional rights are required to unpin all pinned messages. Conversely, the bot must be an administrator with the 'can_pin_messages' right or the 'can_edit_messages' right to unpin all pinned messages in groups and channels respectively. Returns *True* on success.

#### Parameters

| Parameter | Type | Required | Description |
| --- | --- | --- | --- |
| chat_id | Integer or String | Yes | Unique identifier for the target chat or username of the target channel in the format @username |

#### Example

```php

```

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 12.197. unpinAllForumTopicMessages

> Use this method to clear the list of pinned messages in a forum topic in a forum supergroup chat or a private chat with a user

Use this method to clear the list of pinned messages in a forum topic in a forum supergroup chat or a private chat with a user. In the case of a supergroup chat the bot must be an administrator in the chat for this to work and must have the *can_pin_messages* administrator right in the supergroup. Returns *True* on success.

#### Parameters

| Parameter | Type | Required | Description |
| --- | --- | --- | --- |
| chat_id | Integer or String | Yes | Unique identifier for the target chat or username of the target supergroup in the format @username |
| message_thread_id | Integer | Yes | Unique identifier for the target message thread of the forum topic |

#### Example

```php

```

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 12.198. unpinAllGeneralForumTopicMessages

> Use this method to clear the list of pinned messages in a General forum topic

Use this method to clear the list of pinned messages in a General forum topic. The bot must be an administrator in the chat for this to work and must have the *can_pin_messages* administrator right in the supergroup. Returns *True* on success.

#### Parameters

| Parameter | Type | Required | Description |
| --- | --- | --- | --- |
| chat_id | Integer or String | Yes | Unique identifier for the target chat or username of the target supergroup in the format @username |

#### Example

```php

```

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 12.199. unpinChatMessage

> Use this method to remove a message from the list of pinned messages in a chat

Use this method to remove a message from the list of pinned messages in a chat. In private chats and channel direct messages chats, all messages can be unpinned. Conversely, the bot must be an administrator with the 'can_pin_messages' right or the 'can_edit_messages' right to unpin messages in groups and channels respectively. Returns *True* on success.

#### Parameters

| Parameter | Type | Required | Description |
| --- | --- | --- | --- |
| business_connection_id | String | Optional | Unique identifier of the business connection on behalf of which the message will be unpinned |
| chat_id | Integer or String | Yes | Unique identifier for the target chat or username of the target channel in the format @username |
| message_id | Integer | Optional | Identifier of the message to unpin. Required if business_connection_id is specified. If not specified, the most recent pinned message (by sending date) will be unpinned. |

#### Example

```php

```

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 12.200. upgradeGift

> Upgrades a given regular gift to a unique gift

Upgrades a given regular gift to a unique gift. Requires the *can_transfer_and_upgrade_gifts* business bot right. Additionally requires the *can_transfer_stars* business bot right if the upgrade is paid. Returns *True* on success.

#### Parameters

| Parameter | Type | Required | Description |
| --- | --- | --- | --- |
| business_connection_id | String | Yes | Unique identifier of the business connection |
| owned_gift_id | String | Yes | Unique identifier of the regular gift that should be upgraded to a unique one |
| keep_original_details | Boolean | Optional | Pass True to keep the original gift text, sender and receiver in the upgraded gift |
| star_count | Integer | Optional | The amount of Telegram Stars that will be paid for the upgrade from the business account balance. If gift.prepaid_upgrade_star_count > 0, then pass 0, otherwise, the can_transfer_stars business bot right is required and gift.upgrade_star_count must be passed. |

#### Example

```php

```

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 12.201. uploadStickerFile

> Use this method to upload a file with a sticker for later use in the createNewStickerSet, addStickerToSet, or replaceStickerInSet methods (t

Use this method to upload a file with a sticker for later use in the createNewStickerSet, addStickerToSet, or replaceStickerInSet methods (the file can be used multiple times). Returns the uploaded File on success.

#### Parameters

| Parameter | Type | Required | Description |
| --- | --- | --- | --- |
| user_id | Integer | Yes | User identifier of sticker file owner |
| sticker | InputFile | Yes | A file with the sticker in .WEBP, .PNG, .TGS, or .WEBM format. See https://core.telegram.org/stickers for technical requirements. More information on Sending Files » |
| sticker_format | String | Yes | Format of the sticker, must be one of "static", "animated", "video" |

#### Example

```php

```

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 12.202. verifyChat

> Verifies a chat on behalf of the organization which is represented by the bot

Verifies a chat on behalf of the organization which is represented by the bot. Returns *True* on success.

#### Parameters

| Parameter | Type | Required | Description |
| --- | --- | --- | --- |
| chat_id | Integer or String | Yes | Unique identifier for the target chat or username of the target bot, supergroup or channel in the format @username. Channel direct messages chats can't be verified. |
| custom_description | String | Optional | Custom description for the verification; 0-70 characters. Must be empty if the organization isn't allowed to provide a custom verification description. |

#### Example

```php

```

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 12.203. verifyUser

> Verifies a user on behalf of the organization which is represented by the bot

Verifies a user on behalf of the organization which is represented by the bot. Returns *True* on success.

#### Parameters

| Parameter | Type | Required | Description |
| --- | --- | --- | --- |
| user_id | Integer | Yes | Unique identifier of the target user |
| custom_description | String | Optional | Custom description for the verification; 0-70 characters. Must be empty if the organization isn't allowed to provide a custom verification description. |

#### Example

```php

```

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

## 13. 🧩 Complete Telegram Bot API Types Reference (A-Z, 401 Types)

This section provides the complete reference for all Telegram Bot API types. Every type includes structural definitions, field tables, and descriptions.

### 13.1. AcceptedGiftTypes

> This object describes the types of gifts that can be gifted to a user or a chat

This object describes the types of gifts that can be gifted to a user or a chat.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| unlimited_gifts | Boolean | Always | True, if unlimited regular gifts are accepted |
| limited_gifts | Boolean | Always | True, if limited regular gifts are accepted |
| unique_gifts | Boolean | Always | True, if unique gifts or gifts that can be upgraded to unique for free are accepted |
| premium_subscription | Boolean | Always | True, if a Telegram Premium subscription is accepted |
| gifts_from_channels | Boolean | Always | True, if transfers of unique gifts from channels are accepted |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.2. AffiliateInfo

> Contains information about the affiliate that received a commission via this transaction

Contains information about the affiliate that received a commission via this transaction.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| affiliate_user | User | Optional | The bot or the user that received an affiliate commission if it was received by a bot or a user |
| affiliate_chat | Chat | Optional | The chat that received an affiliate commission if it was received by a chat |
| commission_per_mille | Integer | Always | The number of Telegram Stars received by the affiliate for each 1000 Telegram Stars received by the bot from referred users |
| amount | Integer | Always | Integer amount of Telegram Stars received by the affiliate from the transaction, rounded to 0; can be negative for refunds |
| nanostar_amount | Integer | Optional | The number of 1/1000000000 shares of Telegram Stars received by the affiliate; from -999999999 to 999999999; can be negative for refunds |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.3. Animation

> This object represents an animation file (GIF or H.264/MPEG-4 AVC video without sound)

This object represents an animation file (GIF or H.264/MPEG-4 AVC video without sound).

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| file_id | String | Always | Identifier for this file, which can be used to download or reuse the file |
| file_unique_id | String | Always | Unique identifier for this file, which is supposed to be the same over time and for different bots. Can't be used to download or reuse the file. |
| width | Integer | Always | Video width as defined by the sender |
| height | Integer | Always | Video height as defined by the sender |
| duration | Integer | Always | Duration of the video in seconds as defined by the sender |
| thumbnail | PhotoSize | Optional | Animation thumbnail as defined by the sender |
| file_name | String | Optional | Original animation filename as defined by the sender |
| mime_type | String | Optional | MIME type of the file as defined by the sender |
| file_size | Integer | Optional | File size in bytes. It can be bigger than 2^31 and some programming languages may have difficulty/silent defects in interpreting it. But it has at most 52 significant bits, so a signed 64-bit integer or double-precision float type are safe for storing this value. |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.4. Audio

> This object represents an audio file to be treated as music by the Telegram clients

This object represents an audio file to be treated as music by the Telegram clients.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| file_id | String | Always | Identifier for this file, which can be used to download or reuse the file |
| file_unique_id | String | Always | Unique identifier for this file, which is supposed to be the same over time and for different bots. Can't be used to download or reuse the file. |
| duration | Integer | Always | Duration of the audio in seconds as defined by the sender |
| performer | String | Optional | Performer of the audio as defined by the sender or by audio tags |
| title | String | Optional | Title of the audio as defined by the sender or by audio tags |
| file_name | String | Optional | Original filename as defined by the sender |
| mime_type | String | Optional | MIME type of the file as defined by the sender |
| file_size | Integer | Optional | File size in bytes. It can be bigger than 2^31 and some programming languages may have difficulty/silent defects in interpreting it. But it has at most 52 significant bits, so a signed 64-bit integer or double-precision float type are safe for storing this value. |
| thumbnail | PhotoSize | Optional | Thumbnail of the album cover to which the music file belongs |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.5. BackgroundFill

> This object describes the way a background is filled based on the selected colors

This object describes the way a background is filled based on the selected colors. Currently, it can be one of

* BackgroundFillSolid

* BackgroundFillGradient

* BackgroundFillFreeformGradient

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.6. BackgroundFillFreeformGradient

> The background is a freeform gradient that rotates after every message in the chat

The background is a freeform gradient that rotates after every message in the chat.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| type | String | Always | Type of the background fill, always "freeform_gradient" |
| colors | Array of Integer | Always | A list of the 3 or 4 base colors that are used to generate the freeform gradient in the RGB24 format |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.7. BackgroundFillGradient

> The background is a gradient fill

The background is a gradient fill.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| type | String | Always | Type of the background fill, always "gradient" |
| top_color | Integer | Always | Top color of the gradient in the RGB24 format |
| bottom_color | Integer | Always | Bottom color of the gradient in the RGB24 format |
| rotation_angle | Integer | Always | Clockwise rotation angle of the background fill in degrees; 0-359 |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.8. BackgroundFillSolid

> The background is filled using the selected color

The background is filled using the selected color.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| type | String | Always | Type of the background fill, always "solid" |
| color | Integer | Always | The color of the background fill in the RGB24 format |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.9. BackgroundType

> This object describes the type of a background

This object describes the type of a background. Currently, it can be one of

* BackgroundTypeFill

* BackgroundTypeWallpaper

* BackgroundTypePattern

* BackgroundTypeChatTheme

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.10. BackgroundTypeChatTheme

> The background is taken directly from a built-in chat theme

The background is taken directly from a built-in chat theme.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| type | String | Always | Type of the background, always "chat_theme" |
| theme_name | String | Always | Name of the chat theme, which is usually an emoji |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.11. BackgroundTypeFill

> The background is automatically filled based on the selected colors

The background is automatically filled based on the selected colors.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| type | String | Always | Type of the background, always "fill" |
| fill | BackgroundFill | Always | The background fill |
| dark_theme_dimming | Integer | Always | Dimming of the background in dark themes, as a percentage; 0-100 |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.12. BackgroundTypePattern

> The background is a .PNG or .TGV (gzipped subset of SVG with MIME type "application/x-tgwallpattern") pattern to be combined with the backgr

The background is a .PNG or .TGV (gzipped subset of SVG with MIME type "application/x-tgwallpattern") pattern to be combined with the background fill chosen by the user.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| type | String | Always | Type of the background, always "pattern" |
| document | Document | Always | Document with the pattern |
| fill | BackgroundFill | Always | The background fill that is combined with the pattern |
| intensity | Integer | Always | Intensity of the pattern when it is shown above the filled background; 0-100 |
| is_inverted | True | Optional | True, if the background fill must be applied only to the pattern itself. All other pixels are black in this case. For dark themes only. |
| is_moving | True | Optional | True, if the background moves slightly when the device is tilted |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.13. BackgroundTypeWallpaper

> The background is a wallpaper in the JPEG format

The background is a wallpaper in the JPEG format.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| type | String | Always | Type of the background, always "wallpaper" |
| document | Document | Always | Document with the wallpaper |
| dark_theme_dimming | Integer | Always | Dimming of the background in dark themes, as a percentage; 0-100 |
| is_blurred | True | Optional | True, if the wallpaper is downscaled to fit in a 450x450 square and then box-blurred with radius 12 |
| is_moving | True | Optional | True, if the background moves slightly when the device is tilted |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.14. Birthdate

> Describes the birthdate of a user

Describes the birthdate of a user.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| day | Integer | Always | Day of the user's birth; 1-31 |
| month | Integer | Always | Month of the user's birth; 1-12 |
| year | Integer | Optional | Year of the user's birth |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.15. BotAccessSettings

> This object describes the access settings of a bot

This object describes the access settings of a bot.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| is_access_restricted | Boolean | Always | True, if only selected users can access the bot. The bot's owner can always access it. |
| added_users | Array of User | Optional | The list of other users who have access to the bot if the access is restricted |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.16. BotCommand

> This object represents a bot command

This object represents a bot command.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| command | String | Always | Text of the command; 1-32 characters. Can contain only lowercase English letters, digits and underscores. |
| description | String | Always | Description of the command; 1-256 characters |
| is_ephemeral | Boolean | Optional | True, if the command sends an ephemeral message, which can be seen only by the sender of the message and the bot |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.17. BotCommandScope

> This object represents the scope to which bot commands are applied

This object represents the scope to which bot commands are applied. Currently, the following 7 scopes are supported:

* BotCommandScopeDefault

* BotCommandScopeAllPrivateChats

* BotCommandScopeAllGroupChats

* BotCommandScopeAllChatAdministrators

* BotCommandScopeChat

* BotCommandScopeChatAdministrators

* BotCommandScopeChatMember

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.18. BotCommandScopeAllChatAdministrators

> Represents the scope of bot commands, covering all group and supergroup chat administrators

Represents the scope of bot commands, covering all group and supergroup chat administrators.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| type | String | Always | Scope type, must be all_chat_administrators |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.19. BotCommandScopeAllGroupChats

> Represents the scope of bot commands, covering all group and supergroup chats

Represents the scope of bot commands, covering all group and supergroup chats.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| type | String | Always | Scope type, must be all_group_chats |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.20. BotCommandScopeAllPrivateChats

> Represents the scope of bot commands, covering all private chats

Represents the scope of bot commands, covering all private chats.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| type | String | Always | Scope type, must be all_private_chats |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.21. BotCommandScopeChat

> Represents the scope of bot commands, covering a specific chat

Represents the scope of bot commands, covering a specific chat.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| type | String | Always | Scope type, must be chat |
| chat_id | Integer or String | Always | Unique identifier for the target chat or username of the target supergroup in the format @username. Channel direct messages chats and channel chats aren't supported. |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.22. BotCommandScopeChatAdministrators

> Represents the scope of bot commands, covering all administrators of a specific group or supergroup chat

Represents the scope of bot commands, covering all administrators of a specific group or supergroup chat.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| type | String | Always | Scope type, must be chat_administrators |
| chat_id | Integer or String | Always | Unique identifier for the target chat or username of the target supergroup in the format @username. Channel direct messages chats and channel chats aren't supported. |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.23. BotCommandScopeChatMember

> Represents the scope of bot commands, covering a specific member of a group or supergroup chat

Represents the scope of bot commands, covering a specific member of a group or supergroup chat.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| type | String | Always | Scope type, must be chat_member |
| chat_id | Integer or String | Always | Unique identifier for the target chat or username of the target supergroup in the format @username. Channel direct messages chats and channel chats aren't supported. |
| user_id | Integer | Always | Unique identifier of the target user |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.24. BotCommandScopeDefault

> Represents the default scope of bot commands

Represents the default scope of bot commands. Default commands are used if no commands with a narrower scope are specified for the user.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| type | String | Always | Scope type, must be default |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.25. BotDescription

> This object represents the bot's description

This object represents the bot's description.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| description | String | Always | The bot's description |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.26. BotName

> This object represents the bot's name

This object represents the bot's name.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| name | String | Always | The bot's name |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.27. BotShortDescription

> This object represents the bot's short description

This object represents the bot's short description.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| short_description | String | Always | The bot's short description |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.28. BotSubscriptionUpdated

> This object contains information about changes to a user payment subscription toward the current bot

This object contains information about changes to a user payment subscription toward the current bot.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| user | User | Always | User who subscribed for payments toward the bot |
| invoice_payload | String | Always | Bot-specified invoice payload |
| state | String | Always | The new state of the subscription. Currently, it can be one of "canceled" if the user canceled the subscription, "active" if the user re-enabled a previously canceled subscription, or "failed" if payment for the subscription failed. |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.29. BusinessBotRights

> Represents the rights of a business bot

Represents the rights of a business bot.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| can_reply | True | Optional | True, if the bot can send and edit messages in the private chats that had incoming messages in the last 24 hours |
| can_read_messages | True | Optional | True, if the bot can mark incoming private messages as read |
| can_delete_sent_messages | True | Optional | True, if the bot can delete messages sent by the bot |
| can_delete_all_messages | True | Optional | True, if the bot can delete all private messages in managed chats |
| can_edit_name | True | Optional | True, if the bot can edit the first and last name of the business account |
| can_edit_bio | True | Optional | True, if the bot can edit the bio of the business account |
| can_edit_profile_photo | True | Optional | True, if the bot can edit the profile photo of the business account |
| can_edit_username | True | Optional | True, if the bot can edit the username of the business account |
| can_change_gift_settings | True | Optional | True, if the bot can change the privacy settings pertaining to gifts for the business account |
| can_view_gifts_and_stars | True | Optional | True, if the bot can view gifts and the amount of Telegram Stars owned by the business account |
| can_convert_gifts_to_stars | True | Optional | True, if the bot can convert regular gifts owned by the business account to Telegram Stars |
| can_transfer_and_upgrade_gifts | True | Optional | True, if the bot can transfer and upgrade gifts owned by the business account |
| can_transfer_stars | True | Optional | True, if the bot can transfer Telegram Stars received by the business account to its own account, or use them to upgrade and transfer gifts |
| can_manage_stories | True | Optional | True, if the bot can post, edit and delete stories on behalf of the business account |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.30. BusinessConnection

> Describes the connection of the bot with a business account

Describes the connection of the bot with a business account.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| id | String | Always | Unique identifier of the business connection |
| user | User | Always | Business account user that created the business connection |
| user_chat_id | Integer | Always | Identifier of a private chat with the user who created the business connection. This number may have more than 32 significant bits and some programming languages may have difficulty/silent defects in interpreting it. But it has at most 52 significant bits, so a 64-bit integer or double-precision float type are safe for storing this identifier. |
| date | Integer | Always | Date the connection was established in Unix time |
| rights | BusinessBotRights | Optional | Rights of the business bot |
| is_enabled | Boolean | Always | True, if the connection is active |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.31. BusinessIntro

> Contains information about the start page settings of a Telegram Business account

Contains information about the start page settings of a Telegram Business account.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| title | String | Optional | Title text of the business intro |
| message | String | Optional | Message text of the business intro |
| sticker | Sticker | Optional | Sticker of the business intro |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.32. BusinessLocation

> Contains information about the location of a Telegram Business account

Contains information about the location of a Telegram Business account.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| address | String | Always | Address of the business |
| location | Location | Optional | Location of the business |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.33. BusinessMessagesDeleted

> This object is received when messages are deleted from a connected business account

This object is received when messages are deleted from a connected business account.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| business_connection_id | String | Always | Unique identifier of the business connection |
| chat | Chat | Always | Information about a chat in the business account. The bot may not have access to the chat or the corresponding user. |
| message_ids | Array of Integer | Always | The list of identifiers of deleted messages in the chat of the business account |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.34. BusinessOpeningHours

> Describes the opening hours of a business

Describes the opening hours of a business.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| time_zone_name | String | Always | Unique name of the time zone for which the opening hours are defined |
| opening_hours | Array of BusinessOpeningHoursInterval | Always | List of time intervals describing business opening hours |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.35. BusinessOpeningHoursInterval

> Describes an interval of time during which a business is open

Describes an interval of time during which a business is open.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| opening_minute | Integer | Always | The minute's sequence number in a week, starting on Monday, marking the start of the time interval during which the business is open; 0 - 7 * 24 * 60 |
| closing_minute | Integer | Always | The minute's sequence number in a week, starting on Monday, marking the end of the time interval during which the business is open; 0 - 8 \ 24  60 |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.36. CallbackGame

> A placeholder, currently holds no information

A placeholder, currently holds no information. Use BotFather to set up your game.

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.37. CallbackQuery

> This object represents an incoming callback query from a callback button in an inline keyboard

This object represents an incoming callback query from a callback button in an inline keyboard. If the button that originated the query was attached to a message sent by the bot, the field *message* will be present. If the button was attached to a message sent via the bot (in inline mode), the field *inline_message_id* will be present. Exactly one of the fields *data* or *game_short_name* will be present.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| id | String | Always | Unique identifier for this query |
| from | User | Always | Sender |
| message | MaybeInaccessibleMessage | Optional | Message sent by the bot with the callback button that originated the query |
| inline_message_id | String | Optional | Identifier of the message sent via the bot in inline mode, that originated the query |
| chat_instance | String | Always | Global identifier, uniquely corresponding to the chat to which the message with the callback button was sent. Useful for high scores in games. |
| data | String | Optional | Data associated with the callback button. Be aware that the message originated the query can contain no callback buttons with this data. |
| game_short_name | String | Optional | Short name of a Game to be returned, serves as the unique identifier for the game |

> [!NOTE]
> **Official Notes**
> NOTE: After the user presses a callback button, Telegram clients will display a progress bar until you call answerCallbackQuery. It is, therefore, necessary to react by calling answerCallbackQuery even if no notification to the user is needed (e.g., without specifying any of the optional parameters).

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.38. Chat

> This object represents a chat

This object represents a chat.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| id | Integer | Always | Unique identifier for this chat. This number may have more than 32 significant bits and some programming languages may have difficulty/silent defects in interpreting it. But it has at most 52 significant bits, so a signed 64-bit integer or double-precision float type are safe for storing this identifier. |
| type | String | Always | Type of the chat, can be either "private", "group", "supergroup" or "channel" |
| title | String | Optional | Title, for supergroups, channels and group chats |
| username | String | Optional | Username, for private chats, supergroups and channels if available |
| first_name | String | Optional | First name of the other party in a private chat |
| last_name | String | Optional | Last name of the other party in a private chat |
| is_forum | True | Optional | True, if the supergroup chat is a forum (has topics enabled) |
| is_direct_messages | True | Optional | True, if the chat is the direct messages chat of a channel |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.39. ChatAdministratorRights

> Represents the rights of an administrator in a chat

Represents the rights of an administrator in a chat.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| is_anonymous | Boolean | Always | True, if the user's presence in the chat is hidden |
| can_manage_chat | Boolean | Always | True, if the administrator can access the chat event log, get boost list, see hidden supergroup and channel members, report spam messages, ignore slow mode, and send messages to the chat without paying Telegram Stars. Implied by any other administrator privilege. |
| can_delete_messages | Boolean | Always | True, if the administrator can delete messages of other users |
| can_manage_video_chats | Boolean | Always | True, if the administrator can manage video chats |
| can_restrict_members | Boolean | Always | True, if the administrator can restrict, ban or unban chat members, or access supergroup statistics |
| can_promote_members | Boolean | Always | True, if the administrator can add new administrators with a subset of their own privileges or demote administrators that they have promoted, directly or indirectly (promoted by administrators that were appointed by the user) |
| can_change_info | Boolean | Always | True, if the user is allowed to change the chat title, photo and other settings |
| can_invite_users | Boolean | Always | True, if the user is allowed to invite new users to the chat |
| can_post_stories | Boolean | Always | True, if the administrator can post stories to the chat |
| can_edit_stories | Boolean | Always | True, if the administrator can edit stories posted by other users, post stories to the chat page, pin chat stories, and access the chat's story archive |
| can_delete_stories | Boolean | Always | True, if the administrator can delete stories posted by other users |
| can_post_messages | Boolean | Optional | True, if the administrator can post messages in the channel, approve suggested posts, or access channel statistics; for channels only |
| can_edit_messages | Boolean | Optional | True, if the administrator can edit messages of other users and can pin messages; for channels only |
| can_pin_messages | Boolean | Optional | True, if the user is allowed to pin messages; for groups and supergroups only |
| can_manage_topics | Boolean | Optional | True, if the user is allowed to create, rename, close, and reopen forum topics; for supergroups only |
| can_manage_direct_messages | Boolean | Optional | True, if the administrator can manage direct messages of the channel and decline suggested posts; for channels only |
| can_manage_tags | Boolean | Optional | True, if the administrator can edit the tags of regular members; for groups and supergroups only |
| can_send_welcome_messages | Boolean | Always | True, if the administrator can manage chat welcome messages or directly send them in the case of bots |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.40. ChatBackground

> This object represents a chat background

This object represents a chat background.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| type | BackgroundType | Always | Type of the background |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.41. ChatBoost

> This object contains information about a chat boost

This object contains information about a chat boost.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| boost_id | String | Always | Unique identifier of the boost |
| add_date | Integer | Always | Point in time (Unix timestamp) when the chat was boosted |
| expiration_date | Integer | Always | Point in time (Unix timestamp) when the boost will automatically expire, unless the booster's Telegram Premium subscription is prolonged |
| source | ChatBoostSource | Always | Source of the added boost |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.42. ChatBoostAdded

> This object represents a service message about a user boosting a chat

This object represents a service message about a user boosting a chat.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| boost_count | Integer | Always | Number of boosts added by the user |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.43. ChatBoostRemoved

> This object represents a boost removed from a chat

This object represents a boost removed from a chat.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| chat | Chat | Always | Chat which was boosted |
| boost_id | String | Always | Unique identifier of the boost |
| remove_date | Integer | Always | Point in time (Unix timestamp) when the boost was removed |
| source | ChatBoostSource | Always | Source of the removed boost |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.44. ChatBoostSource

> This object describes the source of a chat boost

This object describes the source of a chat boost. It can be one of

* ChatBoostSourcePremium

* ChatBoostSourceGiftCode

* ChatBoostSourceGiveaway

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.45. ChatBoostSourceGiftCode

> The boost was obtained by the creation of Telegram Premium gift codes to boost a chat

The boost was obtained by the creation of Telegram Premium gift codes to boost a chat. Each such code boosts the chat 4 times for the duration of the corresponding Telegram Premium subscription.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| source | String | Always | Source of the boost, always "gift_code" |
| user | User | Always | User for which the gift code was created |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.46. ChatBoostSourceGiveaway

> The boost was obtained by the creation of a Telegram Premium or a Telegram Star giveaway

The boost was obtained by the creation of a Telegram Premium or a Telegram Star giveaway. This boosts the chat 4 times for the duration of the corresponding Telegram Premium subscription for Telegram Premium giveaways and *prize_star_count* / 500 times for one year for Telegram Star giveaways.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| source | String | Always | Source of the boost, always "giveaway" |
| giveaway_message_id | Integer | Always | Identifier of a message in the chat with the giveaway; the message could have been deleted already. May be 0 if the message isn't sent yet. |
| user | User | Optional | User that won the prize in the giveaway if any; for Telegram Premium giveaways only |
| prize_star_count | Integer | Optional | The number of Telegram Stars to be split between giveaway winners; for Telegram Star giveaways only |
| is_unclaimed | True | Optional | True, if the giveaway was completed, but there was no user to win the prize |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.47. ChatBoostSourcePremium

> The boost was obtained by subscribing to Telegram Premium or by gifting a Telegram Premium subscription to another user

The boost was obtained by subscribing to Telegram Premium or by gifting a Telegram Premium subscription to another user.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| source | String | Always | Source of the boost, always "premium" |
| user | User | Always | User that boosted the chat |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.48. ChatBoostUpdated

> This object represents a boost added to a chat or changed

This object represents a boost added to a chat or changed.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| chat | Chat | Always | Chat which was boosted |
| boost | ChatBoost | Always | Information about the chat boost |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.49. ChatFullInfo

> This object contains full information about a chat

This object contains full information about a chat.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| id | Integer | Always | Unique identifier for this chat. This number may have more than 32 significant bits and some programming languages may have difficulty/silent defects in interpreting it. But it has at most 52 significant bits, so a signed 64-bit integer or double-precision float type are safe for storing this identifier. |
| type | String | Always | Type of the chat, can be either "private", "group", "supergroup" or "channel" |
| title | String | Optional | Title, for supergroups, channels and group chats |
| username | String | Optional | Username, for private chats, supergroups and channels if available |
| first_name | String | Optional | First name of the other party in a private chat |
| last_name | String | Optional | Last name of the other party in a private chat |
| is_forum | True | Optional | True, if the supergroup chat is a forum (has topics enabled) |
| is_direct_messages | True | Optional | True, if the chat is the direct messages chat of a channel |
| accent_color_id | Integer | Always | Identifier of the accent color for the chat name and backgrounds of the chat photo, reply header, and link preview. See accent colors for more details. |
| max_reaction_count | Integer | Always | The maximum number of reactions that can be set on a message in the chat |
| photo | ChatPhoto | Optional | Chat photo |
| active_usernames | Array of String | Optional | If non-empty, the list of all active chat usernames; for private chats, supergroups and channels |
| birthdate | Birthdate | Optional | For private chats, the date of birth of the user |
| business_intro | BusinessIntro | Optional | For private chats with business accounts, the intro of the business |
| business_location | BusinessLocation | Optional | For private chats with business accounts, the location of the business |
| business_opening_hours | BusinessOpeningHours | Optional | For private chats with business accounts, the opening hours of the business |
| personal_chat | Chat | Optional | For private chats, the personal channel of the user |
| parent_chat | Chat | Optional | Information about the corresponding channel chat; for direct messages chats only |
| available_reactions | Array of ReactionType | Optional | List of available reactions allowed in the chat. If omitted, then all emoji reactions are allowed. |
| background_custom_emoji_id | String | Optional | Custom emoji identifier of the emoji chosen by the chat for the reply header and link preview background |
| profile_accent_color_id | Integer | Optional | Identifier of the accent color for the chat's profile background. See profile accent colors for more details. |
| profile_background_custom_emoji_id | String | Optional | Custom emoji identifier of the emoji chosen by the chat for its profile background |
| emoji_status_custom_emoji_id | String | Optional | Custom emoji identifier of the emoji status of the chat or the other party in a private chat |
| emoji_status_expiration_date | Integer | Optional | Expiration date of the emoji status of the chat or the other party in a private chat, in Unix time, if any |
| bio | String | Optional | Bio of the other party in a private chat |
| has_private_forwards | True | Optional | True, if privacy settings of the other party in the private chat allows to use tg://user?id= links only in chats with the user |
| has_restricted_voice_and_video_messages | True | Optional | True, if the privacy settings of the other party restrict sending voice and video note messages in the private chat |
| join_to_send_messages | True | Optional | True, if users need to join the supergroup before they can send messages |
| join_by_request | True | Optional | True, if all users directly joining the supergroup without using an invite link need to be approved by supergroup administrators |
| description | String | Optional | Description, for groups, supergroups and channel chats |
| invite_link | String | Optional | Primary invite link, for groups, supergroups and channel chats |
| pinned_message | Message | Optional | The most recent pinned message (by sending date) |
| permissions | ChatPermissions | Optional | Default chat member permissions, for groups and supergroups |
| accepted_gift_types | AcceptedGiftTypes | Always | Information about types of gifts that are accepted by the chat or by the corresponding user for private chats |
| can_send_paid_media | True | Optional | True, if paid media messages can be sent or forwarded to the channel chat. The field is available only for channel chats. |
| slow_mode_delay | Integer | Optional | For supergroups, the minimum allowed delay between consecutive messages sent by each unprivileged user; in seconds |
| unrestrict_boost_count | Integer | Optional | For supergroups, the minimum number of boosts that a non-administrator user needs to add in order to ignore slow mode and chat permissions |
| message_auto_delete_time | Integer | Optional | The time after which all messages sent to the chat will be automatically deleted; in seconds |
| has_aggressive_anti_spam_enabled | True | Optional | True, if aggressive anti-spam checks are enabled in the supergroup. The field is only available to chat administrators. |
| has_hidden_members | True | Optional | True, if non-administrators can only get the list of bots and administrators in the chat |
| has_protected_content | True | Optional | True, if messages from the chat can't be forwarded to other chats |
| has_visible_history | True | Optional | True, if new chat members will have access to old messages; available only to chat administrators |
| sticker_set_name | String | Optional | For supergroups, name of the group sticker set |
| can_set_sticker_set | True | Optional | True, if the bot can change the group sticker set |
| custom_emoji_sticker_set_name | String | Optional | For supergroups, the name of the group's custom emoji sticker set. Custom emoji from this set can be used by all users and bots in the group. |
| linked_chat_id | Integer | Optional | Unique identifier for the linked chat, i.e. the discussion group identifier for a channel and vice versa; for supergroups and channel chats. This identifier may be greater than 32 bits and some programming languages may have difficulty/silent defects in interpreting it. But it is smaller than 52 bits, so a signed 64 bit integer or double-precision float type are safe for storing this identifier. |
| location | ChatLocation | Optional | For supergroups, the location to which the supergroup is connected |
| rating | UserRating | Optional | For private chats, the rating of the user if any |
| first_profile_audio | Audio | Optional | For private chats, the first audio added to the profile of the user |
| unique_gift_colors | UniqueGiftColors | Optional | The color scheme based on a unique gift that must be used for the chat's name, message replies and link previews |
| paid_message_star_count | Integer | Optional | The number of Telegram Stars a general user has to pay to send a message to the chat |
| guard_bot | User | Optional | The bot that processes join request queries in the chat. The field is only available to chat administrators. |
| community | Community | Optional | The Community to which the chat belongs |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.50. ChatInviteLink

> Represents an invite link for a chat

Represents an invite link for a chat.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| invite_link | String | Always | The invite link. If the link was created by another chat administrator, then the second part of the link will be replaced with "...". |
| creator | User | Always | Creator of the link |
| creates_join_request | Boolean | Always | True, if users joining the chat via the link need to be approved by chat administrators |
| is_primary | Boolean | Always | True, if the link is primary |
| is_revoked | Boolean | Always | True, if the link is revoked |
| name | String | Optional | Invite link name |
| expire_date | Integer | Optional | Point in time (Unix timestamp) when the link will expire or has been expired |
| member_limit | Integer | Optional | The maximum number of users that can be members of the chat simultaneously after joining the chat via this invite link; 1-99999 |
| pending_join_request_count | Integer | Optional | Number of pending join requests created using this link |
| subscription_period | Integer | Optional | The number of seconds the subscription will be active for before the next payment |
| subscription_price | Integer | Optional | The amount of Telegram Stars a user must pay initially and after each subsequent subscription period to be a member of the chat using the link |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.51. ChatJoinRequest

> Represents a join request sent to a chat

Represents a join request sent to a chat.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| chat | Chat | Always | Chat to which the request was sent |
| from | User | Always | User that sent the join request |
| user_chat_id | Integer | Always | Identifier of a private chat with the user who sent the join request. This number may have more than 32 significant bits and some programming languages may have difficulty/silent defects in interpreting it. But it has at most 52 significant bits, so a 64-bit integer or double-precision float type are safe for storing this identifier. The bot can use this identifier for 5 minutes to send messages until the join request is processed, assuming no other administrator contacted the user. |
| date | Integer | Always | Date the request was sent in Unix time |
| bio | String | Optional | Bio of the user |
| invite_link | ChatInviteLink | Optional | Chat invite link that was used by the user to send the join request |
| query_id | String | Optional | Identifier of the join request query; for bots assigned to process join requests only. If present, then the bot must call sendChatJoinRequestWebApp or directly call answerChatJoinRequestQuery within 10 seconds. |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.52. ChatLocation

> Represents a location to which a chat is connected

Represents a location to which a chat is connected.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| location | Location | Always | The location to which the supergroup is connected. Can't be a live location. |
| address | String | Always | Location address; 1-64 characters, as defined by the chat owner |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.53. ChatMember

> This object contains information about one member of a chat

This object contains information about one member of a chat. Currently, the following 6 types of chat members are supported:

* ChatMemberOwner

* ChatMemberAdministrator

* ChatMemberMember

* ChatMemberRestricted

* ChatMemberLeft

* ChatMemberBanned

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.54. ChatMemberAdministrator

> Represents a chat member that has some additional privileges

Represents a chat member that has some additional privileges.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| status | String | Always | The member's status in the chat, always "administrator" |
| user | User | Always | Information about the user |
| can_be_edited | Boolean | Always | True, if the bot is allowed to edit administrator privileges of that user |
| is_anonymous | Boolean | Always | True, if the user's presence in the chat is hidden |
| can_manage_chat | Boolean | Always | True, if the administrator can access the chat event log, get boost list, see hidden supergroup and channel members, report spam messages, ignore slow mode, and send messages to the chat without paying Telegram Stars. Implied by any other administrator privilege. |
| can_delete_messages | Boolean | Always | True, if the administrator can delete messages of other users |
| can_manage_video_chats | Boolean | Always | True, if the administrator can manage video chats |
| can_restrict_members | Boolean | Always | True, if the administrator can restrict, ban or unban chat members, or access supergroup statistics |
| can_promote_members | Boolean | Always | True, if the administrator can add new administrators with a subset of their own privileges or demote administrators that they have promoted, directly or indirectly (promoted by administrators that were appointed by the user) |
| can_change_info | Boolean | Always | True, if the user is allowed to change the chat title, photo and other settings |
| can_invite_users | Boolean | Always | True, if the user is allowed to invite new users to the chat |
| can_post_stories | Boolean | Always | True, if the administrator can post stories to the chat |
| can_edit_stories | Boolean | Always | True, if the administrator can edit stories posted by other users, post stories to the chat page, pin chat stories, and access the chat's story archive |
| can_delete_stories | Boolean | Always | True, if the administrator can delete stories posted by other users |
| can_post_messages | Boolean | Optional | True, if the administrator can post messages in the channel, approve suggested posts, or access channel statistics; for channels only |
| can_edit_messages | Boolean | Optional | True, if the administrator can edit messages of other users and can pin messages; for channels only |
| can_pin_messages | Boolean | Optional | True, if the user is allowed to pin messages; for groups and supergroups only |
| can_manage_topics | Boolean | Optional | True, if the user is allowed to create, rename, close, and reopen forum topics; for supergroups only |
| can_manage_direct_messages | Boolean | Optional | True, if the administrator can manage direct messages of the channel and decline suggested posts; for channels only |
| can_manage_tags | Boolean | Optional | True, if the administrator can edit the tags of regular members; for groups and supergroups only |
| can_send_welcome_messages | Boolean | Always | True, if the administrator can manage chat welcome messages or directly send them in the case of bots |
| custom_title | String | Optional | Custom title for this user |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.55. ChatMemberBanned

> Represents a chat member that was banned in the chat and can't return to the chat or view chat messages

Represents a chat member that was banned in the chat and can't return to the chat or view chat messages.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| status | String | Always | The member's status in the chat, always "kicked" |
| user | User | Always | Information about the user |
| until_date | Integer | Always | Date when restrictions will be lifted for this user; Unix time. If 0, then the user is banned forever. |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.56. ChatMemberLeft

> Represents a chat member that isn't currently a member of the chat, but may join it themselves

Represents a chat member that isn't currently a member of the chat, but may join it themselves.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| status | String | Always | The member's status in the chat, always "left" |
| user | User | Always | Information about the user |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.57. ChatMemberMember

> Represents a chat member that has no additional privileges or restrictions

Represents a chat member that has no additional privileges or restrictions.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| status | String | Always | The member's status in the chat, always "member" |
| tag | String | Optional | Tag of the member |
| user | User | Always | Information about the user |
| until_date | Integer | Optional | Date when the user's subscription will expire; Unix time |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.58. ChatMemberOwner

> Represents a chat member that owns the chat and has all administrator privileges

Represents a chat member that owns the chat and has all administrator privileges.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| status | String | Always | The member's status in the chat, always "creator" |
| user | User | Always | Information about the user |
| is_anonymous | Boolean | Always | True, if the user's presence in the chat is hidden |
| custom_title | String | Optional | Custom title for this user |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.59. ChatMemberRestricted

> Represents a chat member that is under certain restrictions in the chat

Represents a chat member that is under certain restrictions in the chat. Supergroups only.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| status | String | Always | The member's status in the chat, always "restricted" |
| tag | String | Optional | Tag of the member |
| user | User | Always | Information about the user |
| is_member | Boolean | Always | True, if the user is a member of the chat at the moment of the request |
| can_send_messages | Boolean | Always | True, if the user is allowed to send text messages, rich messages, contacts, giveaways, giveaway winners, invoices, locations and venues |
| can_send_audios | Boolean | Always | True, if the user is allowed to send audios |
| can_send_documents | Boolean | Always | True, if the user is allowed to send documents |
| can_send_photos | Boolean | Always | True, if the user is allowed to send photos |
| can_send_videos | Boolean | Always | True, if the user is allowed to send videos |
| can_send_video_notes | Boolean | Always | True, if the user is allowed to send video notes |
| can_send_voice_notes | Boolean | Always | True, if the user is allowed to send voice notes |
| can_send_polls | Boolean | Always | True, if the user is allowed to send polls and checklists |
| can_send_other_messages | Boolean | Always | True, if the user is allowed to send animations, games, stickers and use inline bots |
| can_add_web_page_previews | Boolean | Always | True, if the user is allowed to add web page previews to their messages |
| can_react_to_messages | Boolean | Always | True, if the user is allowed to react to messages |
| can_edit_tag | Boolean | Always | True, if the user is allowed to edit their own tag |
| can_change_info | Boolean | Always | True, if the user is allowed to change the chat title, photo and other settings |
| can_invite_users | Boolean | Always | True, if the user is allowed to invite new users to the chat |
| can_pin_messages | Boolean | Always | True, if the user is allowed to pin messages |
| can_manage_topics | Boolean | Always | True, if the user is allowed to create forum topics |
| until_date | Integer | Always | Date when restrictions will be lifted for this user; Unix time. If 0, then the user is restricted forever. |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.60. ChatMemberUpdated

> This object represents changes in the status of a chat member

This object represents changes in the status of a chat member.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| chat | Chat | Always | Chat the user belongs to |
| from | User | Always | Performer of the action, which resulted in the change |
| date | Integer | Always | Date the change was done in Unix time |
| old_chat_member | ChatMember | Always | Previous information about the chat member |
| new_chat_member | ChatMember | Always | New information about the chat member |
| invite_link | ChatInviteLink | Optional | Chat invite link, which was used by the user to join the chat; for joining by invite link events only |
| via_join_request | Boolean | Optional | True, if the user joined the chat after sending a direct join request without using an invite link and being approved by an administrator |
| via_chat_folder_invite_link | Boolean | Optional | True, if the user joined the chat via a chat folder invite link |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.61. ChatOwnerChanged

> Describes a service message about an ownership change in the chat

Describes a service message about an ownership change in the chat.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| new_owner | User | Always | The new owner of the chat |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.62. ChatOwnerLeft

> Describes a service message about the chat owner leaving the chat

Describes a service message about the chat owner leaving the chat.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| new_owner | User | Optional | The user who will become the new owner of the chat if the previous owner does not return to the chat |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.63. ChatPermissions

> Describes actions that a non-administrator user is allowed to take in a chat

Describes actions that a non-administrator user is allowed to take in a chat.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| can_send_messages | Boolean | Optional | True, if the user is allowed to send text messages, rich messages, contacts, giveaways, giveaway winners, invoices, locations and venues |
| can_send_audios | Boolean | Optional | True, if the user is allowed to send audios |
| can_send_documents | Boolean | Optional | True, if the user is allowed to send documents |
| can_send_photos | Boolean | Optional | True, if the user is allowed to send photos |
| can_send_videos | Boolean | Optional | True, if the user is allowed to send videos |
| can_send_video_notes | Boolean | Optional | True, if the user is allowed to send video notes |
| can_send_voice_notes | Boolean | Optional | True, if the user is allowed to send voice notes |
| can_send_polls | Boolean | Optional | True, if the user is allowed to send polls and checklists |
| can_send_other_messages | Boolean | Optional | True, if the user is allowed to send animations, games, stickers and use inline bots |
| can_add_web_page_previews | Boolean | Optional | True, if the user is allowed to add web page previews to their messages |
| can_react_to_messages | Boolean | Optional | True, if the user is allowed to react to messages. If omitted, defaults to the value of can_send_messages. |
| can_edit_tag | Boolean | Optional | True, if the user is allowed to edit their own tag. If omitted, defaults to the value of can_pin_messages. |
| can_change_info | Boolean | Optional | True, if the user is allowed to change the chat title, photo and other settings. Ignored in public supergroups. |
| can_invite_users | Boolean | Optional | True, if the user is allowed to invite new users to the chat |
| can_pin_messages | Boolean | Optional | True, if the user is allowed to pin messages. Ignored in public supergroups. |
| can_manage_topics | Boolean | Optional | True, if the user is allowed to create forum topics. If omitted, defaults to the value of can_pin_messages. |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.64. ChatPhoto

> This object represents a chat photo

This object represents a chat photo.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| small_file_id | String | Always | File identifier of small (160x160) chat photo. This file_id can be used only for photo download and only for as long as the photo is not changed. |
| small_file_unique_id | String | Always | Unique file identifier of small (160x160) chat photo, which is supposed to be the same over time and for different bots. Can't be used to download or reuse the file. |
| big_file_id | String | Always | File identifier of big (640x640) chat photo. This file_id can be used only for photo download and only for as long as the photo is not changed. |
| big_file_unique_id | String | Always | Unique file identifier of big (640x640) chat photo, which is supposed to be the same over time and for different bots. Can't be used to download or reuse the file. |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.65. ChatShared

> This object contains information about a chat that was shared with the bot using a KeyboardButtonRequestChat button

This object contains information about a chat that was shared with the bot using a KeyboardButtonRequestChat button.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| request_id | Integer | Always | Identifier of the request |
| chat_id | Integer | Always | Identifier of the shared chat. This number may have more than 32 significant bits and some programming languages may have difficulty/silent defects in interpreting it. But it has at most 52 significant bits, so a 64-bit integer or double-precision float type are safe for storing this identifier. The bot may not have access to the chat and could be unable to use this identifier, unless the chat is already known to the bot by some other means. |
| title | String | Optional | Title of the chat, if the title was requested by the bot |
| username | String | Optional | Username of the chat, if the username was requested by the bot and available |
| photo | Array of PhotoSize | Optional | Available sizes of the chat photo, if the photo was requested by the bot |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.66. Checklist

> Describes a checklist

Describes a checklist.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| title | String | Always | Title of the checklist |
| title_entities | Array of MessageEntity | Optional | Special entities that appear in the checklist title |
| tasks | Array of ChecklistTask | Always | List of tasks in the checklist |
| others_can_add_tasks | True | Optional | True, if users other than the creator of the list can add tasks to the list |
| others_can_mark_tasks_as_done | True | Optional | True, if users other than the creator of the list can mark tasks as done or not done |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.67. ChecklistTask

> Describes a task in a checklist

Describes a task in a checklist.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| id | Integer | Always | Unique identifier of the task |
| text | String | Always | Text of the task |
| text_entities | Array of MessageEntity | Optional | Special entities that appear in the task text |
| completed_by_user | User | Optional | User that completed the task; omitted if the task wasn't completed by a user |
| completed_by_chat | Chat | Optional | Chat that completed the task; omitted if the task wasn't completed by a chat |
| completion_date | Integer | Optional | Point in time (Unix timestamp) when the task was completed; 0 if the task wasn't completed |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.68. ChecklistTasksAdded

> Describes a service message about tasks added to a checklist

Describes a service message about tasks added to a checklist.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| checklist_message | Message | Optional | Message containing the checklist to which the tasks were added. Note that the Message object in this field will not contain the reply_to_message field even if it itself is a reply. |
| tasks | Array of ChecklistTask | Always | List of tasks added to the checklist |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.69. ChecklistTasksDone

> Describes a service message about checklist tasks marked as done or not done

Describes a service message about checklist tasks marked as done or not done.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| checklist_message | Message | Optional | Message containing the checklist whose tasks were marked as done or not done. Note that the Message object in this field will not contain the reply_to_message field even if it itself is a reply. |
| marked_as_done_task_ids | Array of Integer | Optional | Identifiers of the tasks that were marked as done |
| marked_as_not_done_task_ids | Array of Integer | Optional | Identifiers of the tasks that were marked as not done |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.70. ChosenInlineResult

> Represents a result of an inline query that was chosen by the user and sent to their chat partner

Represents a result of an inline query that was chosen by the user and sent to their chat partner.

**Note:** It is necessary to enable inline feedback via @BotFather in order to receive these objects in updates.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| result_id | String | Always | The unique identifier for the result that was chosen |
| from | User | Always | The user that chose the result |
| location | Location | Optional | Sender location, only for bots that require user location |
| inline_message_id | String | Optional | Identifier of the sent inline message. Available only if there is an inline keyboard attached to the message. Will be also received in callback queries and can be used to edit the message. |
| query | String | Always | The query that was used to obtain the result |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.71. Community

> Represents a community (a group of chats)

Represents a community (a group of chats).

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| id | Integer | Always | Unique identifier for this community. This number may have more than 32 significant bits and some programming languages may have difficulty/silent defects in interpreting it. But it has at most 52 significant bits, so a signed 64-bit integer or double-precision float type are safe for storing this identifier. |
| name | String | Always | Name of the community |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.72. CommunityChatAdded

> Describes a service message about a chat or a bot being added to a community

Describes a service message about a chat or a bot being added to a community.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| community | Community | Always | The new community to which the chat or the bot belongs |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.73. CommunityChatJoined

> Describes a service message about a chat being joined by a user from a community

Describes a service message about a chat being joined by a user from a community.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| community | Community | Always | The community from which the chat was joined |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.74. CommunityChatRemoved

> Describes a service message about a chat or a bot being removed from a community

Describes a service message about a chat or a bot being removed from a community. Currently holds no information.

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.75. Contact

> This object represents a phone contact

This object represents a phone contact.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| phone_number | String | Always | Contact's phone number |
| first_name | String | Always | Contact's first name |
| last_name | String | Optional | Contact's last name |
| user_id | Integer | Optional | Contact's user identifier in Telegram. This number may have more than 32 significant bits and some programming languages may have difficulty/silent defects in interpreting it. But it has at most 52 significant bits, so a 64-bit integer or double-precision float type are safe for storing this identifier. |
| vcard | String | Optional | Additional data about the contact in the form of a vCard |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.76. CopyTextButton

> This object represents an inline keyboard button that copies specified text to the clipboard

This object represents an inline keyboard button that copies specified text to the clipboard.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| text | String | Always | The text to be copied to the clipboard; 1-256 characters |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.77. Dice

> This object represents an animated emoji that displays a random value

This object represents an animated emoji that displays a random value.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| emoji | String | Always | Emoji on which the dice throw animation is based |
| value | Integer | Always | Value of the dice, 1-6 for "🎲", "🎯" and "🎳" base emoji, 1-5 for "🏀" and "⚽" base emoji, 1-64 for "🎰" base emoji |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.78. DirectMessagePriceChanged

> Describes a service message about a change in the price of direct messages sent to a channel chat

Describes a service message about a change in the price of direct messages sent to a channel chat.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| are_direct_messages_enabled | Boolean | Always | True, if direct messages are enabled for the channel chat; False otherwise |
| direct_message_star_count | Integer | Optional | The new number of Telegram Stars that must be paid by users for each direct message sent to the channel. Does not apply to users who have been exempted by administrators. Defaults to 0. |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.79. DirectMessagesTopic

> Describes a topic of a direct messages chat

Describes a topic of a direct messages chat.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| topic_id | Integer | Always | Unique identifier of the topic. This number may have more than 32 significant bits and some programming languages may have difficulty/silent defects in interpreting it. But it has at most 52 significant bits, so a 64-bit integer or double-precision float type are safe for storing this identifier. |
| user | User | Optional | Information about the user that created the topic. Currently, it is always present. |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.80. DisabledButton

> This object represents a disabled button which does nothing

This object represents a disabled button which does nothing. Currently holds no information.

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.81. Document

> This object represents a general file (as opposed to photos, voice messages and audio files)

This object represents a general file (as opposed to photos, voice messages and audio files).

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| file_id | String | Always | Identifier for this file, which can be used to download or reuse the file |
| file_unique_id | String | Always | Unique identifier for this file, which is supposed to be the same over time and for different bots. Can't be used to download or reuse the file. |
| thumbnail | PhotoSize | Optional | Document thumbnail as defined by the sender |
| file_name | String | Optional | Original filename as defined by the sender |
| mime_type | String | Optional | MIME type of the file as defined by the sender |
| file_size | Integer | Optional | File size in bytes. It can be bigger than 2^31 and some programming languages may have difficulty/silent defects in interpreting it. But it has at most 52 significant bits, so a signed 64-bit integer or double-precision float type are safe for storing this value. |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.82. EncryptedCredentials

> Describes data required for decrypting and authenticating EncryptedPassportElement

Describes data required for decrypting and authenticating EncryptedPassportElement. See the Telegram Passport Documentation for a complete description of the data decryption and authentication processes.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| data | String | Always | Base64-encoded encrypted JSON-serialized data with unique user's payload, data hashes and secrets required for EncryptedPassportElement decryption and authentication |
| hash | String | Always | Base64-encoded data hash for data authentication |
| secret | String | Always | Base64-encoded secret, encrypted with the bot's public RSA key, required for data decryption |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.83. EncryptedPassportElement

> Describes documents or other Telegram Passport elements shared with the bot by the user

Describes documents or other Telegram Passport elements shared with the bot by the user.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| type | String | Always | Element type. One of "personal_details", "passport", "driver_license", "identity_card", "internal_passport", "address", "utility_bill", "bank_statement", "rental_agreement", "passport_registration", "temporary_registration", "phone_number", "email". |
| data | String | Optional | Base64-encoded encrypted Telegram Passport element data provided by the user; available only for "personal_details", "passport", "driver_license", "identity_card", "internal_passport" and "address" types. Can be decrypted and verified using the accompanying EncryptedCredentials. |
| phone_number | String | Optional | User's verified phone number; available only for "phone_number" type |
| email | String | Optional | User's verified email address; available only for "email" type |
| files | Array of PassportFile | Optional | Array of encrypted files with documents provided by the user; available only for "utility_bill", "bank_statement", "rental_agreement", "passport_registration" and "temporary_registration" types. Files can be decrypted and verified using the accompanying EncryptedCredentials. |
| front_side | PassportFile | Optional | Encrypted file with the front side of the document, provided by the user; available only for "passport", "driver_license", "identity_card" and "internal_passport". The file can be decrypted and verified using the accompanying EncryptedCredentials. |
| reverse_side | PassportFile | Optional | Encrypted file with the reverse side of the document, provided by the user; available only for "driver_license" and "identity_card". The file can be decrypted and verified using the accompanying EncryptedCredentials. |
| selfie | PassportFile | Optional | Encrypted file with the selfie of the user holding a document, provided by the user; available if requested for "passport", "driver_license", "identity_card" and "internal_passport". The file can be decrypted and verified using the accompanying EncryptedCredentials. |
| translation | Array of PassportFile | Optional | Array of encrypted files with translated versions of documents provided by the user; available if requested for "passport", "driver_license", "identity_card", "internal_passport", "utility_bill", "bank_statement", "rental_agreement", "passport_registration" and "temporary_registration" types. Files can be decrypted and verified using the accompanying EncryptedCredentials. |
| hash | String | Always | Base64-encoded element hash for using in PassportElementErrorUnspecified |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.84. EphemeralMessageParameters

> Describes the parameters of an ephemeral message sent back to a specific user without cluttering the chat for other members.

Describes the parameters of an ephemeral message sent back to a specific user. Other members of the group or supergroup will not see the message.

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| receiver_user_id | Integer | Always | Identifier of the user who will receive the message. It is not guaranteed that the user will receive the message, especially if they are offline. See here for more details. |
| callback_query_id | String | Optional | Identifier of the callback query which triggered the message, if any |
| replace_callback_query_message | Boolean | Optional | Pass *True* if the ephemeral message must be shown in place of the original message. Must be *False* for callback queries from ephemeral messages, which must be edited using regular *editEphemeralMessage...* methods. |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.85. ExternalReplyInfo

> This object contains information about a message that is being replied to, which may come from another chat or forum topic

This object contains information about a message that is being replied to, which may come from another chat or forum topic.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| origin | MessageOrigin | Always | Origin of the message replied to by the given message |
| chat | Chat | Optional | Chat the original message belongs to. Available only if the chat is a supergroup or a channel. |
| message_id | Integer | Optional | Unique message identifier inside the original chat. Available only if the original chat is a supergroup or a channel. |
| link_preview_options | LinkPreviewOptions | Optional | Options used for link preview generation for the original message, if it is a text message |
| animation | Animation | Optional | Message is an animation, information about the animation |
| audio | Audio | Optional | Message is an audio file, information about the file |
| document | Document | Optional | Message is a general file, information about the file |
| live_photo | LivePhoto | Optional | Message is a live photo, information about the live photo |
| paid_media | PaidMediaInfo | Optional | Message contains paid media; information about the paid media |
| photo | Array of PhotoSize | Optional | Message is a photo, available sizes of the photo |
| sticker | Sticker | Optional | Message is a sticker, information about the sticker |
| story | Story | Optional | Message is a forwarded story |
| video | Video | Optional | Message is a video, information about the video |
| video_note | VideoNote | Optional | Message is a video note, information about the video message |
| voice | Voice | Optional | Message is a voice message, information about the file |
| has_media_spoiler | True | Optional | True, if the message media is covered by a spoiler animation |
| checklist | Checklist | Optional | Message is a checklist |
| contact | Contact | Optional | Message is a shared contact, information about the contact |
| dice | Dice | Optional | Message is a dice with random value |
| game | Game | Optional | Message is a game, information about the game. More about games » |
| giveaway | Giveaway | Optional | Message is a scheduled giveaway, information about the giveaway |
| giveaway_winners | GiveawayWinners | Optional | A giveaway with public winners was completed |
| invoice | Invoice | Optional | Message is an invoice for a payment, information about the invoice. More about payments » |
| location | Location | Optional | Message is a shared location, information about the location |
| poll | Poll | Optional | Message is a native poll, information about the poll |
| venue | Venue | Optional | Message is a venue, information about the venue |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.86. File

> This object represents a file ready to be downloaded

This object represents a file ready to be downloaded. The file can be downloaded via the link `https://api.telegram.org/file/bot<token>/<file_path>`. It is guaranteed that the link will be valid for at least 1 hour. When the link expires, a new one can be requested by calling getFile.

The maximum file size to download is 20 MB

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| file_id | String | Always | Identifier for this file, which can be used to download or reuse the file |
| file_unique_id | String | Always | Unique identifier for this file, which is supposed to be the same over time and for different bots. Can't be used to download or reuse the file. |
| file_size | Integer | Optional | File size in bytes. It can be bigger than 2^31 and some programming languages may have difficulty/silent defects in interpreting it. But it has at most 52 significant bits, so a signed 64-bit integer or double-precision float type are safe for storing this value. |
| file_path | String | Optional | File path. Use https://api.telegram.org/file/bot/ to get the file. |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.87. ForceReply

> Upon receiving a message with this object, Telegram clients will display a reply interface to the user (act as if the user has selected the 

Upon receiving a message with this object, Telegram clients will display a reply interface to the user (act as if the user has selected the bot's message and tapped 'Reply'). This can be extremely useful if you want to create user-friendly step-by-step interfaces without having to sacrifice privacy mode. Not supported in channels and for messages sent on behalf of a user account.

- Explain the user how to send a command with parameters (e.g. /newpoll question answer1 answer2). May be appealing for hardcore users but lacks modern day polish.

- Guide the user through a step-by-step process. 'Please send me your question', 'Cool, now let's add the first answer option', 'Great. Keep adding answer options, then send /done when you're ready'.

The last option is definitely more attractive. And if you use ForceReply in your bot's questions, it will receive the user's answers even if it only receives replies, commands and mentions - without any extra work for the user.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| force_reply | True | Always | Shows reply interface to the user, as if they had manually selected the bot's message and tapped 'Reply' |
| input_field_placeholder | String | Optional | The placeholder to be shown in the input field when the reply is active; 1-64 characters |
| selective | Boolean | Optional | Use this parameter if you want to force reply from specific users only. Targets: 1) users that are @mentioned in the text of the Message object; 2) if the bot's message is a reply to a message in the same chat and forum topic, sender of the original message. |

#### Example

```php
{"force_reply": true, "input_field_placeholder": "Enter your name…"}
```

> [!NOTE]
> **Official Notes**
> Example: A poll bot for groups runs in privacy mode (only receives commands, replies to its messages and mentions). There could be two ways to create a new poll:

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.88. ForumTopic

> This object represents a forum topic

This object represents a forum topic.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| message_thread_id | Integer | Always | Unique identifier of the forum topic |
| name | String | Always | Name of the topic |
| icon_color | Integer | Always | Color of the topic icon in RGB format |
| icon_custom_emoji_id | String | Optional | Unique identifier of the custom emoji shown as the topic icon |
| is_name_implicit | True | Optional | True, if the name of the topic wasn't specified explicitly by its creator and likely needs to be changed by the bot |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.89. ForumTopicClosed

> This object represents a service message about a forum topic closed in the chat

This object represents a service message about a forum topic closed in the chat. Currently holds no information.

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.90. ForumTopicCreated

> This object represents a service message about a new forum topic created in the chat

This object represents a service message about a new forum topic created in the chat.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| name | String | Always | Name of the topic |
| icon_color | Integer | Always | Color of the topic icon in RGB format |
| icon_custom_emoji_id | String | Optional | Unique identifier of the custom emoji shown as the topic icon |
| is_name_implicit | True | Optional | True, if the name of the topic wasn't specified explicitly by its creator and likely needs to be changed by the bot |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.91. ForumTopicEdited

> This object represents a service message about an edited forum topic

This object represents a service message about an edited forum topic.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| name | String | Optional | New name of the topic, if it was edited |
| icon_custom_emoji_id | String | Optional | New identifier of the custom emoji shown as the topic icon, if it was edited; an empty string if the icon was removed |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.92. ForumTopicReopened

> This object represents a service message about a forum topic reopened in the chat

This object represents a service message about a forum topic reopened in the chat. Currently holds no information.

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.93. Game

> This object represents a game

This object represents a game. Use BotFather to create and edit games, their short names will act as unique identifiers.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| title | String | Always | Title of the game |
| description | String | Always | Description of the game |
| photo | Array of PhotoSize | Always | Photo that will be displayed in the game message in chats |
| text | String | Optional | Brief description of the game or high scores included in the game message. Can be automatically edited to include current high scores for the game when the bot calls setGameScore, or manually edited using editMessageText. 0-4096 characters. |
| text_entities | Array of MessageEntity | Optional | Special entities that appear in text, such as usernames, URLs, bot commands, etc. |
| animation | Animation | Optional | Animation that will be displayed in the game message in chats. Upload via BotFather. |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.94. GameHighScore

> This object represents one row of the high scores table for a game

This object represents one row of the high scores table for a game.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| position | Integer | Always | Position in high score table for the game |
| user | User | Always | User |
| score | Integer | Always | Score |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.95. GeneralForumTopicHidden

> This object represents a service message about General forum topic hidden in the chat

This object represents a service message about General forum topic hidden in the chat. Currently holds no information.

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.96. GeneralForumTopicUnhidden

> This object represents a service message about General forum topic unhidden in the chat

This object represents a service message about General forum topic unhidden in the chat. Currently holds no information.

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.97. Gift

> This object represents a gift that can be sent by the bot

This object represents a gift that can be sent by the bot.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| id | String | Always | Unique identifier of the gift |
| sticker | Sticker | Always | The sticker that represents the gift |
| star_count | Integer | Always | The number of Telegram Stars that must be paid to send the sticker |
| upgrade_star_count | Integer | Optional | The number of Telegram Stars that must be paid to upgrade the gift to a unique one |
| is_premium | True | Optional | True, if the gift can only be purchased by Telegram Premium subscribers |
| has_colors | True | Optional | True, if the gift can be used (after being upgraded) to customize a user's appearance |
| total_count | Integer | Optional | The total number of gifts of this type that can be sent by all users; for limited gifts only |
| remaining_count | Integer | Optional | The number of remaining gifts of this type that can be sent by all users; for limited gifts only |
| personal_total_count | Integer | Optional | The total number of gifts of this type that can be sent by the bot; for limited gifts only |
| personal_remaining_count | Integer | Optional | The number of remaining gifts of this type that can be sent by the bot; for limited gifts only |
| background | GiftBackground | Optional | Background of the gift |
| unique_gift_variant_count | Integer | Optional | The total number of different unique gifts that can be obtained by upgrading the gift |
| publisher_chat | Chat | Optional | Information about the chat that published the gift |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.98. GiftBackground

> This object describes the background of a gift

This object describes the background of a gift.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| center_color | Integer | Always | Center color of the background in RGB format |
| edge_color | Integer | Always | Edge color of the background in RGB format |
| text_color | Integer | Always | Text color of the background in RGB format |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.99. GiftInfo

> Describes a service message about a regular gift that was sent or received

Describes a service message about a regular gift that was sent or received.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| gift | Gift | Always | Information about the gift |
| owned_gift_id | String | Optional | Unique identifier of the received gift for the bot; only present for gifts received on behalf of business accounts |
| convert_star_count | Integer | Optional | Number of Telegram Stars that can be claimed by the receiver by converting the gift; omitted if conversion to Telegram Stars is impossible |
| prepaid_upgrade_star_count | Integer | Optional | Number of Telegram Stars that were prepaid for the ability to upgrade the gift |
| is_upgrade_separate | True | Optional | True, if the gift's upgrade was purchased after the gift was sent |
| can_be_upgraded | True | Optional | True, if the gift can be upgraded to a unique gift |
| text | String | Optional | Text of the message that was added to the gift |
| entities | Array of MessageEntity | Optional | Special entities that appear in the text |
| is_private | True | Optional | True, if the sender and gift text are shown only to the gift receiver; otherwise, everyone will be able to see them |
| unique_gift_number | Integer | Optional | Unique number reserved for this gift when upgraded. See the number field in UniqueGift. |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.100. Gifts

> This object represent a list of gifts

This object represent a list of gifts.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| gifts | Array of Gift | Always | The list of gifts |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.101. Giveaway

> This object represents a message about a scheduled giveaway

This object represents a message about a scheduled giveaway.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| chats | Array of Chat | Always | The list of chats which the user must join to participate in the giveaway |
| winners_selection_date | Integer | Always | Point in time (Unix timestamp) when winners of the giveaway will be selected |
| winner_count | Integer | Always | The number of users which are supposed to be selected as winners of the giveaway |
| only_new_members | True | Optional | True, if only users who join the chats after the giveaway started should be eligible to win |
| has_public_winners | True | Optional | True, if the list of giveaway winners will be visible to everyone |
| prize_description | String | Optional | Description of additional giveaway prize |
| country_codes | Array of String | Optional | A list of two-letter ISO 3166-1 alpha-2 country codes indicating the countries from which eligible users for the giveaway must come. If empty, then all users can participate in the giveaway. Users with a phone number that was bought on Fragment can always participate in giveaways. |
| prize_star_count | Integer | Optional | The number of Telegram Stars to be split between giveaway winners; for Telegram Star giveaways only |
| premium_subscription_month_count | Integer | Optional | The number of months the Telegram Premium subscription won from the giveaway will be active for; for Telegram Premium giveaways only |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.102. GiveawayCompleted

> This object represents a service message about the completion of a giveaway without public winners

This object represents a service message about the completion of a giveaway without public winners.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| winner_count | Integer | Always | Number of winners in the giveaway |
| unclaimed_prize_count | Integer | Optional | Number of undistributed prizes |
| giveaway_message | Message | Optional | Message with the giveaway that was completed, if it wasn't deleted |
| is_star_giveaway | True | Optional | True, if the giveaway is a Telegram Star giveaway. Otherwise, currently, the giveaway is a Telegram Premium giveaway. |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.103. GiveawayCreated

> This object represents a service message about the creation of a scheduled giveaway

This object represents a service message about the creation of a scheduled giveaway.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| prize_star_count | Integer | Optional | The number of Telegram Stars to be split between giveaway winners; for Telegram Star giveaways only |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.104. GiveawayWinners

> This object represents a message about the completion of a giveaway with public winners

This object represents a message about the completion of a giveaway with public winners.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| chat | Chat | Always | The chat that created the giveaway |
| giveaway_message_id | Integer | Always | Identifier of the message with the giveaway in the chat |
| winners_selection_date | Integer | Always | Point in time (Unix timestamp) when winners of the giveaway were selected |
| winner_count | Integer | Always | Total number of winners in the giveaway |
| winners | Array of User | Always | List of up to 100 winners of the giveaway |
| additional_chat_count | Integer | Optional | The number of other chats the user had to join in order to be eligible for the giveaway |
| prize_star_count | Integer | Optional | The number of Telegram Stars that were split between giveaway winners; for Telegram Star giveaways only |
| premium_subscription_month_count | Integer | Optional | The number of months the Telegram Premium subscription won from the giveaway will be active for; for Telegram Premium giveaways only |
| unclaimed_prize_count | Integer | Optional | Number of undistributed prizes |
| only_new_members | True | Optional | True, if only users who had joined the chats after the giveaway started were eligible to win |
| was_refunded | True | Optional | True, if the giveaway was canceled because the payment for it was refunded |
| prize_description | String | Optional | Description of additional giveaway prize |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.105. InaccessibleMessage

> This object describes a message that was deleted or is otherwise inaccessible to the bot

This object describes a message that was deleted or is otherwise inaccessible to the bot.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| chat | Chat | Always | Chat the message belonged to |
| message_id | Integer | Always | Unique message identifier inside the chat |
| date | Integer | Always | Always 0. The field can be used to differentiate regular and inaccessible messages. |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.106. InlineKeyboardButton

> This object represents one button of an inline keyboard

This object represents one button of an inline keyboard. Exactly one of the fields other than *text*, *icon_custom_emoji_id*, and *style* must be used to specify the type of the button.

This offers a quick way for the user to open your bot in inline mode in the same chat - good for selecting something from multiple options. Not supported in channels and for messages sent in channel direct messages chats and on behalf of a business account.

**NOTE:** This type of button **must** always be the first button in the first row.

**NOTE:** This type of button **must** always be the first button in the first row and can only be used in invoice messages.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| text | String | Always | Label text on the button |
| icon_custom_emoji_id | String | Optional | Unique identifier of the custom emoji shown before the text of the button. Can only be used by bots that purchased additional usernames on Fragment or in the messages directly sent by the bot to private, group and supergroup chats if the owner of the bot has a Telegram Premium subscription. |
| style | String | Optional | Style of the button. Must be one of "danger" (red), "success" (green) or "primary" (blue). If omitted, then an app-specific style is used. |
| url | String | Optional | HTTP or tg:// URL to be opened when the button is pressed. Links tg://user?id= can be used to mention a user by their identifier without using a username, if this is allowed by their privacy settings. |
| callback_data | String | Optional | Data to be sent in a callback query to the bot when the button is pressed, 1-64 bytes |
| web_app | WebAppInfo | Optional | Description of the Web App that will be launched when the user presses the button. The Web App will be able to send an arbitrary message on behalf of the user using the method answerWebAppQuery. Available only in private chats between a user and the bot. Not supported for messages sent on behalf of a business account. |
| login_url | LoginUrl | Optional | An HTTPS URL used to automatically authorize the user. Can be used as a replacement for the Telegram Login Widget. Not supported for ephemeral messages. |
| switch_inline_query | String | Optional | If set, pressing the button will prompt the user to select one of their chats, open that chat and insert the bot's username and the specified inline query in the input field. May be empty, in which case just the bot's username will be inserted. Not supported for messages sent in channel direct messages chats and on behalf of a business account. |
| switch_inline_query_current_chat | String | Optional | If set, pressing the button will insert the bot's username and the specified inline query in the current chat's input field. May be empty, in which case only the bot's username will be inserted. |

#### Example

```php
{"text": "✅ Approve", "callback_data": "approve_42"}
```

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.107. InlineKeyboardMarkup

> This object represents an inline keyboard that appears right next to the message it belongs to

This object represents an inline keyboard that appears right next to the message it belongs to.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| inline_keyboard | Array of Array of InlineKeyboardButton | Always | Array of button rows, each represented by an Array of InlineKeyboardButton objects |
| force_reply | Boolean | Optional | Pass True if the reply interface must be shown to the user, as if they had manually selected the bot's message and tapped 'Reply'. The value of the field can't be changed when the inline keyboard is edited. |

#### Example

```php
{
  "inline_keyboard": [
    [
      {"text": "👍 Like", "callback_data": "like_123"},
      {"text": "🔗 Open Site", "url": "https://botlify.cloud"}
    ],
    [
      {"text": "💳 Pay with Stars", "pay": true}
    ]
  ]
}
```

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.108. InlineQuery

> This object represents an incoming inline query

This object represents an incoming inline query. When the user sends an empty query, your bot could return some default or trending results.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| id | String | Always | Unique identifier for this query |
| from | User | Always | Sender |
| query | String | Always | Text of the query (up to 256 characters) |
| offset | String | Always | Offset of the results to be returned, can be controlled by the bot |
| chat_type | String | Optional | Type of the chat from which the inline query was sent. Can be either "sender" for a private chat with the inline query sender, "private", "group", "supergroup", or "channel". The chat type should be always known for requests sent from official clients and most third-party clients, unless the request was sent from a secret chat. |
| location | Location | Optional | Sender location, only for bots that request user location |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.109. InlineQueryResult

> This object represents one result of an inline query

This object represents one result of an inline query. Telegram clients currently support results of the following 20 types:

* InlineQueryResultCachedAudio

* InlineQueryResultCachedDocument

* InlineQueryResultCachedGif

* InlineQueryResultCachedMpeg4Gif

* InlineQueryResultCachedPhoto

* InlineQueryResultCachedSticker

* InlineQueryResultCachedVideo

* InlineQueryResultCachedVoice

* InlineQueryResultArticle

* InlineQueryResultAudio

* InlineQueryResultContact

* InlineQueryResultGame

* InlineQueryResultDocument

* InlineQueryResultGif

* InlineQueryResultLocation

* InlineQueryResultMpeg4Gif

* InlineQueryResultPhoto

* InlineQueryResultVenue

* InlineQueryResultVideo

* InlineQueryResultVoice

**Note:** All URLs passed in inline query results will be available to end users and therefore must be assumed to be **public**.

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.110. InlineQueryResultArticle

> Represents a link to an article or web page

Represents a link to an article or web page.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| type | String | Always | Type of the result, must be article |
| id | String | Always | Unique identifier for this result, 1-64 Bytes |
| title | String | Always | Title of the result |
| input_message_content | InputMessageContent | Always | Content of the message to be sent |
| reply_markup | InlineKeyboardMarkup | Optional | Inline keyboard attached to the message |
| url | String | Optional | URL of the result |
| description | String | Optional | Short description of the result |
| thumbnail_url | String | Optional | Url of the thumbnail for the result |
| thumbnail_width | Integer | Optional | Thumbnail width |
| thumbnail_height | Integer | Optional | Thumbnail height |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.111. InlineQueryResultAudio

> Represents a link to an MP3 audio file

Represents a link to an MP3 audio file. By default, this audio file will be sent by the user. Alternatively, you can use *input_message_content* to send a message with the specified content instead of the audio.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| type | String | Always | Type of the result, must be audio |
| id | String | Always | Unique identifier for this result, 1-64 bytes |
| audio_url | String | Always | A valid URL for the audio file |
| title | String | Always | Title |
| caption | String | Optional | Caption, 0-1024 characters after entities parsing |
| parse_mode | String | Optional | Mode for parsing entities in the audio caption. See formatting options for more details. |
| caption_entities | Array of MessageEntity | Optional | List of special entities that appear in the caption, which can be specified instead of parse_mode |
| performer | String | Optional | Performer |
| audio_duration | Integer | Optional | Audio duration in seconds |
| reply_markup | InlineKeyboardMarkup | Optional | Inline keyboard attached to the message |
| input_message_content | InputMessageContent | Optional | Content of the message to be sent instead of the audio |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.112. InlineQueryResultCachedAudio

> Represents a link to an MP3 audio file stored on the Telegram servers

Represents a link to an MP3 audio file stored on the Telegram servers. By default, this audio file will be sent by the user. Alternatively, you can use *input_message_content* to send a message with the specified content instead of the audio.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| type | String | Always | Type of the result, must be audio |
| id | String | Always | Unique identifier for this result, 1-64 bytes |
| audio_file_id | String | Always | A valid file identifier for the audio file |
| caption | String | Optional | Caption, 0-1024 characters after entities parsing |
| parse_mode | String | Optional | Mode for parsing entities in the audio caption. See formatting options for more details. |
| caption_entities | Array of MessageEntity | Optional | List of special entities that appear in the caption, which can be specified instead of parse_mode |
| reply_markup | InlineKeyboardMarkup | Optional | Inline keyboard attached to the message |
| input_message_content | InputMessageContent | Optional | Content of the message to be sent instead of the audio |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.113. InlineQueryResultCachedDocument

> Represents a link to a file stored on the Telegram servers

Represents a link to a file stored on the Telegram servers. By default, this file will be sent by the user with an optional caption. Alternatively, you can use *input_message_content* to send a message with the specified content instead of the file.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| type | String | Always | Type of the result, must be document |
| id | String | Always | Unique identifier for this result, 1-64 bytes |
| title | String | Always | Title for the result |
| document_file_id | String | Always | A valid file identifier for the file |
| description | String | Optional | Short description of the result |
| caption | String | Optional | Caption of the document to be sent, 0-1024 characters after entities parsing |
| parse_mode | String | Optional | Mode for parsing entities in the document caption. See formatting options for more details. |
| caption_entities | Array of MessageEntity | Optional | List of special entities that appear in the caption, which can be specified instead of parse_mode |
| reply_markup | InlineKeyboardMarkup | Optional | Inline keyboard attached to the message |
| input_message_content | InputMessageContent | Optional | Content of the message to be sent instead of the file |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.114. InlineQueryResultCachedGif

> Represents a link to an animated GIF file stored on the Telegram servers

Represents a link to an animated GIF file stored on the Telegram servers. By default, this animated GIF file will be sent by the user with an optional caption. Alternatively, you can use *input_message_content* to send a message with specified content instead of the animation.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| type | String | Always | Type of the result, must be gif |
| id | String | Always | Unique identifier for this result, 1-64 bytes |
| gif_file_id | String | Always | A valid file identifier for the GIF file |
| title | String | Optional | Title for the result |
| caption | String | Optional | Caption of the GIF file to be sent, 0-1024 characters after entities parsing |
| parse_mode | String | Optional | Mode for parsing entities in the caption. See formatting options for more details. |
| caption_entities | Array of MessageEntity | Optional | List of special entities that appear in the caption, which can be specified instead of parse_mode |
| show_caption_above_media | Boolean | Optional | Pass True if the caption must be shown above the message media |
| reply_markup | InlineKeyboardMarkup | Optional | Inline keyboard attached to the message |
| input_message_content | InputMessageContent | Optional | Content of the message to be sent instead of the GIF animation |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.115. InlineQueryResultCachedMpeg4Gif

> Represents a link to a video animation (H.264/MPEG-4 AVC video without sound) stored on the Telegram servers

Represents a link to a video animation (H.264/MPEG-4 AVC video without sound) stored on the Telegram servers. By default, this animated MPEG-4 file will be sent by the user with an optional caption. Alternatively, you can use *input_message_content* to send a message with the specified content instead of the animation.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| type | String | Always | Type of the result, must be mpeg4_gif |
| id | String | Always | Unique identifier for this result, 1-64 bytes |
| mpeg4_file_id | String | Always | A valid file identifier for the MPEG4 file |
| title | String | Optional | Title for the result |
| caption | String | Optional | Caption of the MPEG-4 file to be sent, 0-1024 characters after entities parsing |
| parse_mode | String | Optional | Mode for parsing entities in the caption. See formatting options for more details. |
| caption_entities | Array of MessageEntity | Optional | List of special entities that appear in the caption, which can be specified instead of parse_mode |
| show_caption_above_media | Boolean | Optional | Pass True if the caption must be shown above the message media |
| reply_markup | InlineKeyboardMarkup | Optional | Inline keyboard attached to the message |
| input_message_content | InputMessageContent | Optional | Content of the message to be sent instead of the video animation |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.116. InlineQueryResultCachedPhoto

> Represents a link to a photo stored on the Telegram servers

Represents a link to a photo stored on the Telegram servers. By default, this photo will be sent by the user with an optional caption. Alternatively, you can use *input_message_content* to send a message with the specified content instead of the photo.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| type | String | Always | Type of the result, must be photo |
| id | String | Always | Unique identifier for this result, 1-64 bytes |
| photo_file_id | String | Always | A valid file identifier of the photo |
| title | String | Optional | Title for the result |
| description | String | Optional | Short description of the result |
| caption | String | Optional | Caption of the photo to be sent, 0-1024 characters after entities parsing |
| parse_mode | String | Optional | Mode for parsing entities in the photo caption. See formatting options for more details. |
| caption_entities | Array of MessageEntity | Optional | List of special entities that appear in the caption, which can be specified instead of parse_mode |
| show_caption_above_media | Boolean | Optional | Pass True if the caption must be shown above the message media |
| reply_markup | InlineKeyboardMarkup | Optional | Inline keyboard attached to the message |
| input_message_content | InputMessageContent | Optional | Content of the message to be sent instead of the photo |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.117. InlineQueryResultCachedSticker

> Represents a link to a sticker stored on the Telegram servers

Represents a link to a sticker stored on the Telegram servers. By default, this sticker will be sent by the user. Alternatively, you can use *input_message_content* to send a message with the specified content instead of the sticker.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| type | String | Always | Type of the result, must be sticker |
| id | String | Always | Unique identifier for this result, 1-64 bytes |
| sticker_file_id | String | Always | A valid file identifier of the sticker |
| reply_markup | InlineKeyboardMarkup | Optional | Inline keyboard attached to the message |
| input_message_content | InputMessageContent | Optional | Content of the message to be sent instead of the sticker |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.118. InlineQueryResultCachedVideo

> Represents a link to a video file stored on the Telegram servers

Represents a link to a video file stored on the Telegram servers. By default, this video file will be sent by the user with an optional caption. Alternatively, you can use *input_message_content* to send a message with the specified content instead of the video.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| type | String | Always | Type of the result, must be video |
| id | String | Always | Unique identifier for this result, 1-64 bytes |
| video_file_id | String | Always | A valid file identifier for the video file |
| title | String | Always | Title for the result |
| description | String | Optional | Short description of the result |
| caption | String | Optional | Caption of the video to be sent, 0-1024 characters after entities parsing |
| parse_mode | String | Optional | Mode for parsing entities in the video caption. See formatting options for more details. |
| caption_entities | Array of MessageEntity | Optional | List of special entities that appear in the caption, which can be specified instead of parse_mode |
| show_caption_above_media | Boolean | Optional | Pass True if the caption must be shown above the message media |
| reply_markup | InlineKeyboardMarkup | Optional | Inline keyboard attached to the message |
| input_message_content | InputMessageContent | Optional | Content of the message to be sent instead of the video |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.119. InlineQueryResultCachedVoice

> Represents a link to a voice message stored on the Telegram servers

Represents a link to a voice message stored on the Telegram servers. By default, this voice message will be sent by the user. Alternatively, you can use *input_message_content* to send a message with the specified content instead of the voice message.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| type | String | Always | Type of the result, must be voice |
| id | String | Always | Unique identifier for this result, 1-64 bytes |
| voice_file_id | String | Always | A valid file identifier for the voice message |
| title | String | Always | Voice message title |
| caption | String | Optional | Caption, 0-1024 characters after entities parsing |
| parse_mode | String | Optional | Mode for parsing entities in the voice message caption. See formatting options for more details. |
| caption_entities | Array of MessageEntity | Optional | List of special entities that appear in the caption, which can be specified instead of parse_mode |
| reply_markup | InlineKeyboardMarkup | Optional | Inline keyboard attached to the message |
| input_message_content | InputMessageContent | Optional | Content of the message to be sent instead of the voice message |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.120. InlineQueryResultContact

> Represents a contact with a phone number

Represents a contact with a phone number. By default, this contact will be sent by the user. Alternatively, you can use *input_message_content* to send a message with the specified content instead of the contact.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| type | String | Always | Type of the result, must be contact |
| id | String | Always | Unique identifier for this result, 1-64 Bytes |
| phone_number | String | Always | Contact's phone number |
| first_name | String | Always | Contact's first name |
| last_name | String | Optional | Contact's last name |
| vcard | String | Optional | Additional data about the contact in the form of a vCard, 0-2048 bytes |
| reply_markup | InlineKeyboardMarkup | Optional | Inline keyboard attached to the message |
| input_message_content | InputMessageContent | Optional | Content of the message to be sent instead of the contact |
| thumbnail_url | String | Optional | Url of the thumbnail for the result |
| thumbnail_width | Integer | Optional | Thumbnail width |
| thumbnail_height | Integer | Optional | Thumbnail height |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.121. InlineQueryResultDocument

> Represents a link to a file

Represents a link to a file. By default, this file will be sent by the user with an optional caption. Alternatively, you can use *input_message_content* to send a message with the specified content instead of the file. Currently, only **.PDF** and **.ZIP** files can be sent using this method.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| type | String | Always | Type of the result, must be document |
| id | String | Always | Unique identifier for this result, 1-64 bytes |
| title | String | Always | Title for the result |
| caption | String | Optional | Caption of the document to be sent, 0-1024 characters after entities parsing |
| parse_mode | String | Optional | Mode for parsing entities in the document caption. See formatting options for more details. |
| caption_entities | Array of MessageEntity | Optional | List of special entities that appear in the caption, which can be specified instead of parse_mode |
| document_url | String | Always | A valid URL for the file |
| mime_type | String | Always | MIME type of the content of the file, either "application/pdf" or "application/zip" |
| description | String | Optional | Short description of the result |
| reply_markup | InlineKeyboardMarkup | Optional | Inline keyboard attached to the message |
| input_message_content | InputMessageContent | Optional | Content of the message to be sent instead of the file |
| thumbnail_url | String | Optional | URL of the thumbnail (JPEG only) for the file |
| thumbnail_width | Integer | Optional | Thumbnail width |
| thumbnail_height | Integer | Optional | Thumbnail height |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.122. InlineQueryResultGame

> Represents a Game.

Represents a Game.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| type | String | Always | Type of the result, must be game |
| id | String | Always | Unique identifier for this result, 1-64 bytes |
| game_short_name | String | Always | Short name of the game |
| reply_markup | InlineKeyboardMarkup | Optional | Inline keyboard attached to the message |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.123. InlineQueryResultGif

> Represents a link to an animated GIF file

Represents a link to an animated GIF file. By default, this animated GIF file will be sent by the user with optional caption. Alternatively, you can use *input_message_content* to send a message with the specified content instead of the animation.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| type | String | Always | Type of the result, must be gif |
| id | String | Always | Unique identifier for this result, 1-64 bytes |
| gif_url | String | Always | A valid URL for the GIF file |
| gif_width | Integer | Optional | Width of the GIF |
| gif_height | Integer | Optional | Height of the GIF |
| gif_duration | Integer | Optional | Duration of the GIF in seconds |
| thumbnail_url | String | Always | URL of the static (JPEG or GIF) or animated (MPEG4) thumbnail for the result |
| thumbnail_mime_type | String | Optional | MIME type of the thumbnail, must be one of "image/jpeg", "image/gif", or "video/mp4". Defaults to "image/jpeg". |
| title | String | Optional | Title for the result |
| caption | String | Optional | Caption of the GIF file to be sent, 0-1024 characters after entities parsing |
| parse_mode | String | Optional | Mode for parsing entities in the caption. See formatting options for more details. |
| caption_entities | Array of MessageEntity | Optional | List of special entities that appear in the caption, which can be specified instead of parse_mode |
| show_caption_above_media | Boolean | Optional | Pass True if the caption must be shown above the message media |
| reply_markup | InlineKeyboardMarkup | Optional | Inline keyboard attached to the message |
| input_message_content | InputMessageContent | Optional | Content of the message to be sent instead of the GIF animation |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.124. InlineQueryResultLocation

> Represents a location on a map

Represents a location on a map. By default, the location will be sent by the user. Alternatively, you can use *input_message_content* to send a message with the specified content instead of the location.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| type | String | Always | Type of the result, must be location |
| id | String | Always | Unique identifier for this result, 1-64 Bytes |
| latitude | Float | Always | Location latitude in degrees |
| longitude | Float | Always | Location longitude in degrees |
| title | String | Always | Location title |
| horizontal_accuracy | Float | Optional | The radius of uncertainty for the location, measured in meters; 0-1500 |
| live_period | Integer | Optional | Period in seconds during which the location can be updated, must be between 60 and 86400, or 0x7FFFFFFF for live locations that can be edited indefinitely |
| heading | Integer | Optional | For live locations, a direction in which the user is moving, in degrees. Must be between 1 and 360 if specified. |
| proximity_alert_radius | Integer | Optional | For live locations, a maximum distance for proximity alerts about approaching another chat member, in meters. Must be between 1 and 100000 if specified. |
| reply_markup | InlineKeyboardMarkup | Optional | Inline keyboard attached to the message |
| input_message_content | InputMessageContent | Optional | Content of the message to be sent instead of the location |
| thumbnail_url | String | Optional | Url of the thumbnail for the result |
| thumbnail_width | Integer | Optional | Thumbnail width |
| thumbnail_height | Integer | Optional | Thumbnail height |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.125. InlineQueryResultMpeg4Gif

> Represents a link to a video animation (H.264/MPEG-4 AVC video without sound)

Represents a link to a video animation (H.264/MPEG-4 AVC video without sound). By default, this animated MPEG-4 file will be sent by the user with optional caption. Alternatively, you can use *input_message_content* to send a message with the specified content instead of the animation.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| type | String | Always | Type of the result, must be mpeg4_gif |
| id | String | Always | Unique identifier for this result, 1-64 bytes |
| mpeg4_url | String | Always | A valid URL for the MPEG4 file |
| mpeg4_width | Integer | Optional | Video width |
| mpeg4_height | Integer | Optional | Video height |
| mpeg4_duration | Integer | Optional | Video duration in seconds |
| thumbnail_url | String | Always | URL of the static (JPEG or GIF) or animated (MPEG4) thumbnail for the result |
| thumbnail_mime_type | String | Optional | MIME type of the thumbnail, must be one of "image/jpeg", "image/gif", or "video/mp4". Defaults to "image/jpeg". |
| title | String | Optional | Title for the result |
| caption | String | Optional | Caption of the MPEG-4 file to be sent, 0-1024 characters after entities parsing |
| parse_mode | String | Optional | Mode for parsing entities in the caption. See formatting options for more details. |
| caption_entities | Array of MessageEntity | Optional | List of special entities that appear in the caption, which can be specified instead of parse_mode |
| show_caption_above_media | Boolean | Optional | Pass True if the caption must be shown above the message media |
| reply_markup | InlineKeyboardMarkup | Optional | Inline keyboard attached to the message |
| input_message_content | InputMessageContent | Optional | Content of the message to be sent instead of the video animation |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.126. InlineQueryResultPhoto

> Represents a link to a photo

Represents a link to a photo. By default, this photo will be sent by the user with optional caption. Alternatively, you can use *input_message_content* to send a message with the specified content instead of the photo.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| type | String | Always | Type of the result, must be photo |
| id | String | Always | Unique identifier for this result, 1-64 bytes |
| photo_url | String | Always | A valid URL of the photo. Photo must be in JPEG format. Photo size must not exceed 5MB. |
| thumbnail_url | String | Always | URL of the thumbnail for the photo |
| photo_width | Integer | Optional | Width of the photo |
| photo_height | Integer | Optional | Height of the photo |
| title | String | Optional | Title for the result |
| description | String | Optional | Short description of the result |
| caption | String | Optional | Caption of the photo to be sent, 0-1024 characters after entities parsing |
| parse_mode | String | Optional | Mode for parsing entities in the photo caption. See formatting options for more details. |
| caption_entities | Array of MessageEntity | Optional | List of special entities that appear in the caption, which can be specified instead of parse_mode |
| show_caption_above_media | Boolean | Optional | Pass True if the caption must be shown above the message media |
| reply_markup | InlineKeyboardMarkup | Optional | Inline keyboard attached to the message |
| input_message_content | InputMessageContent | Optional | Content of the message to be sent instead of the photo |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.127. InlineQueryResultsButton

> This object represents a button to be shown above inline query results

This object represents a button to be shown above inline query results. You **must** use exactly one of the optional fields.

*Example:* An inline bot that sends YouTube videos can ask the user to connect the bot to their YouTube account to adapt search results accordingly. To do this, it displays a 'Connect your YouTube account' button above the results, or even before showing any. The user presses the button, switches to a private chat with the bot and, in doing so, passes a start parameter that instructs the bot to return an OAuth link. Once done, the bot can offer a *switch_inline* button so that the user can easily return to the chat where they wanted to use the bot's inline capabilities.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| text | String | Always | Label text on the button |
| web_app | WebAppInfo | Optional | Description of the Web App that will be launched when the user presses the button. The Web App will be able to switch back to the inline mode using the method switchInlineQuery inside the Web App. |
| start_parameter | String | Optional | Deep-linking parameter for the /start message sent to the bot when a user presses the button. 1-64 characters, only A-Z, a-z, 0-9, _ and - are allowed. |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.128. InlineQueryResultVenue

> Represents a venue. By default, the venue will be sent by the user

Represents a venue. By default, the venue will be sent by the user. Alternatively, you can use *input_message_content* to send a message with the specified content instead of the venue.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| type | String | Always | Type of the result, must be venue |
| id | String | Always | Unique identifier for this result, 1-64 Bytes |
| latitude | Float | Always | Latitude of the venue location in degrees |
| longitude | Float | Always | Longitude of the venue location in degrees |
| title | String | Always | Title of the venue |
| address | String | Always | Address of the venue |
| foursquare_id | String | Optional | Foursquare identifier of the venue if known |
| foursquare_type | String | Optional | Foursquare type of the venue, if known. (For example, "arts_entertainment/default", "arts_entertainment/aquarium" or "food/icecream".) |
| google_place_id | String | Optional | Google Places identifier of the venue |
| google_place_type | String | Optional | Google Places type of the venue. (See supported types.) |
| reply_markup | InlineKeyboardMarkup | Optional | Inline keyboard attached to the message |
| input_message_content | InputMessageContent | Optional | Content of the message to be sent instead of the venue |
| thumbnail_url | String | Optional | Url of the thumbnail for the result |
| thumbnail_width | Integer | Optional | Thumbnail width |
| thumbnail_height | Integer | Optional | Thumbnail height |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.129. InlineQueryResultVideo

> Represents a link to a page containing an embedded video player or a video file

Represents a link to a page containing an embedded video player or a video file. By default, this video file will be sent by the user with an optional caption. Alternatively, you can use *input_message_content* to send a message with the specified content instead of the video.

If an InlineQueryResultVideo message contains an embedded video (e.g., YouTube), you **must** replace its content using *input_message_content*.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| type | String | Always | Type of the result, must be video |
| id | String | Always | Unique identifier for this result, 1-64 bytes |
| video_url | String | Always | A valid URL for the embedded video player or video file |
| mime_type | String | Always | MIME type of the content of the video URL, "text/html" or "video/mp4" |
| thumbnail_url | String | Always | URL of the thumbnail (JPEG only) for the video |
| title | String | Always | Title for the result |
| caption | String | Optional | Caption of the video to be sent, 0-1024 characters after entities parsing |
| parse_mode | String | Optional | Mode for parsing entities in the video caption. See formatting options for more details. |
| caption_entities | Array of MessageEntity | Optional | List of special entities that appear in the caption, which can be specified instead of parse_mode |
| show_caption_above_media | Boolean | Optional | Pass True if the caption must be shown above the message media |
| video_width | Integer | Optional | Video width |
| video_height | Integer | Optional | Video height |
| video_duration | Integer | Optional | Video duration in seconds |
| description | String | Optional | Short description of the result |
| reply_markup | InlineKeyboardMarkup | Optional | Inline keyboard attached to the message |
| input_message_content | InputMessageContent | Optional | Content of the message to be sent instead of the video. This field is required if InlineQueryResultVideo is used to send an HTML-page as a result (e.g., a YouTube video). |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.130. InlineQueryResultVoice

> Represents a link to a voice recording in an .OGG container encoded with OPUS

Represents a link to a voice recording in an .OGG container encoded with OPUS. By default, this voice recording will be sent by the user. Alternatively, you can use *input_message_content* to send a message with the specified content instead of the the voice message.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| type | String | Always | Type of the result, must be voice |
| id | String | Always | Unique identifier for this result, 1-64 bytes |
| voice_url | String | Always | A valid URL for the voice recording |
| title | String | Always | Recording title |
| caption | String | Optional | Caption, 0-1024 characters after entities parsing |
| parse_mode | String | Optional | Mode for parsing entities in the voice message caption. See formatting options for more details. |
| caption_entities | Array of MessageEntity | Optional | List of special entities that appear in the caption, which can be specified instead of parse_mode |
| voice_duration | Integer | Optional | Recording duration in seconds |
| reply_markup | InlineKeyboardMarkup | Optional | Inline keyboard attached to the message |
| input_message_content | InputMessageContent | Optional | Content of the message to be sent instead of the voice recording |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.131. InputChecklist

> Describes a checklist to create

Describes a checklist to create.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| title | String | Always | Title of the checklist; 1-255 characters after entities parsing |
| parse_mode | String | Optional | Mode for parsing entities in the title. See formatting options for more details. |
| title_entities | Array of MessageEntity | Optional | List of special entities that appear in the title, which can be specified instead of parse_mode. Currently, only bold, italic, underline, strikethrough, spoiler, custom_emoji, and date_time entities are allowed. |
| tasks | Array of InputChecklistTask | Always | List of 1-30 tasks in the checklist |
| others_can_add_tasks | Boolean | Optional | Pass True if other users can add tasks to the checklist |
| others_can_mark_tasks_as_done | Boolean | Optional | Pass True if other users can mark tasks as done or not done in the checklist |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.132. InputChecklistTask

> Describes a task to add to a checklist

Describes a task to add to a checklist.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| id | Integer | Always | Unique identifier of the task; must be positive and unique among all task identifiers currently present in the checklist |
| text | String | Always | Text of the task; 1-100 characters after entities parsing |
| parse_mode | String | Optional | Mode for parsing entities in the text. See formatting options for more details. |
| text_entities | Array of MessageEntity | Optional | List of special entities that appear in the text, which can be specified instead of parse_mode. Currently, only bold, italic, underline, strikethrough, spoiler, custom_emoji, and date_time entities are allowed. |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.133. InputContactMessageContent

> Represents the content of a contact message to be sent as the result of an inline query

Represents the content of a contact message to be sent as the result of an inline query.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| phone_number | String | Always | Contact's phone number |
| first_name | String | Always | Contact's first name |
| last_name | String | Optional | Contact's last name |
| vcard | String | Optional | Additional data about the contact in the form of a vCard, 0-2048 bytes |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.134. InputFile

> This object represents the contents of a file to be uploaded

This object represents the contents of a file to be uploaded. Must be posted using multipart/form-data in the usual way that files are uploaded via the browser.

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.135. InputInvoiceMessageContent

> Represents the content of an invoice message to be sent as the result of an inline query

Represents the content of an invoice message to be sent as the result of an inline query.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| title | String | Always | Product name, 1-32 characters |
| description | String | Always | Product description, 1-255 characters |
| payload | String | Always | Bot-defined invoice payload, 1-128 bytes. This will not be displayed to the user, use it for your internal processes. |
| provider_token | String | Optional | Payment provider token, obtained via @BotFather. Pass an empty string for payments in Telegram Stars. |
| currency | String | Always | Three-letter ISO 4217 currency code, see more on currencies. Pass "XTR" for payments in Telegram Stars. |
| prices | Array of LabeledPrice | Always | Price breakdown, a JSON-serialized list of components (e.g. product price, tax, discount, delivery cost, delivery tax, bonus, etc.). Must contain exactly one item for payments in Telegram Stars. |
| max_tip_amount | Integer | Optional | The maximum accepted amount for tips in the smallest units of the currency (integer, not float/double). For example, for a maximum tip of US$ 1.45 pass max_tip_amount = 145. See the exp parameter in currencies.json, it shows the number of digits past the decimal point for each currency (2 for the majority of currencies). Defaults to 0. Not supported for payments in Telegram Stars. |
| suggested_tip_amounts | Array of Integer | Optional | A JSON-serialized Array of suggested amounts of tip in the smallest units of the currency (integer, not float/double). At most 4 suggested tip amounts can be specified. The suggested tip amounts must be positive, passed in a strictly increased order and must not exceed max_tip_amount. |
| provider_data | String | Optional | A JSON-serialized object for data about the invoice, which will be shared with the payment provider. A detailed description of the required fields should be provided by the payment provider. |
| photo_url | String | Optional | URL of the product photo for the invoice. Can be a photo of the goods or a marketing image for a service. |
| photo_size | Integer | Optional | Photo size in bytes |
| photo_width | Integer | Optional | Photo width |
| photo_height | Integer | Optional | Photo height |
| need_name | Boolean | Optional | Pass True if you require the user's full name to complete the order. Ignored for payments in Telegram Stars. |
| need_phone_number | Boolean | Optional | Pass True if you require the user's phone number to complete the order. Ignored for payments in Telegram Stars. |
| need_email | Boolean | Optional | Pass True if you require the user's email address to complete the order. Ignored for payments in Telegram Stars. |
| need_shipping_address | Boolean | Optional | Pass True if you require the user's shipping address to complete the order. Ignored for payments in Telegram Stars. |
| send_phone_number_to_provider | Boolean | Optional | Pass True if the user's phone number should be sent to the provider. Ignored for payments in Telegram Stars. |
| send_email_to_provider | Boolean | Optional | Pass True if the user's email address should be sent to the provider. Ignored for payments in Telegram Stars. |
| is_flexible | Boolean | Optional | Pass True if the final price depends on the shipping method. Ignored for payments in Telegram Stars. |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.136. InputLocationMessageContent

> Represents the content of a location message to be sent as the result of an inline query

Represents the content of a location message to be sent as the result of an inline query.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| latitude | Float | Always | Latitude of the location in degrees |
| longitude | Float | Always | Longitude of the location in degrees |
| horizontal_accuracy | Float | Optional | The radius of uncertainty for the location, measured in meters; 0-1500 |
| live_period | Integer | Optional | Period in seconds during which the location can be updated, must be between 60 and 86400, or 0x7FFFFFFF for live locations that can be edited indefinitely |
| heading | Integer | Optional | For live locations, a direction in which the user is moving, in degrees. Must be between 1 and 360 if specified. |
| proximity_alert_radius | Integer | Optional | For live locations, a maximum distance for proximity alerts about approaching another chat member, in meters. Must be between 1 and 100000 if specified. |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.137. InputMedia

> This object represents the content of a media message to be sent

This object represents the content of a media message to be sent. It should be one of

* InputMediaAnimation

* InputMediaAudio

* InputMediaDocument

* InputMediaLivePhoto

* InputMediaPhoto

* InputMediaVideo

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.138. InputMediaAnimation

> Represents an animation file (GIF or H.264/MPEG-4 AVC video without sound) to be sent

Represents an animation file (GIF or H.264/MPEG-4 AVC video without sound) to be sent.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| type | String | Always | Type of the media, must be animation |
| media | String | Always | File to send. Pass a file_id to send a file that exists on the Telegram servers (recommended), pass an HTTP URL for Telegram to get a file from the Internet, or pass "attach://<file_attach_name>" to upload a new one using multipart/form-data under <file_attach_name> name. More information on Sending Files » |
| thumbnail | String | Optional | Thumbnail of the file sent; can be ignored if thumbnail generation for the file is supported server-side. The thumbnail should be in JPEG format and less than 200 kB in size. A thumbnail's width and height should not exceed 320. Ignored if the file is not uploaded using multipart/form-data. Thumbnails can't be reused and can be only uploaded as a new file, so you can pass "attach://<file_attach_name>" if the thumbnail was uploaded using multipart/form-data under <file_attach_name>. More information on Sending Files » |
| caption | String | Optional | Caption of the animation to be sent, 0-1024 characters after entities parsing |
| parse_mode | String | Optional | Mode for parsing entities in the animation caption. See formatting options for more details. |
| caption_entities | Array of MessageEntity | Optional | List of special entities that appear in the caption, which can be specified instead of parse_mode |
| show_caption_above_media | Boolean | Optional | Pass True if the caption must be shown above the message media |
| width | Integer | Optional | Animation width |
| height | Integer | Optional | Animation height |
| duration | Integer | Optional | Animation duration in seconds |
| has_spoiler | Boolean | Optional | Pass True if the animation needs to be covered with a spoiler animation |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.139. InputMediaAudio

> Represents an audio file to be treated as music to be sent

Represents an audio file to be treated as music to be sent.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| type | String | Always | Type of the media, must be audio |
| media | String | Always | File to send. Pass a file_id to send a file that exists on the Telegram servers (recommended), pass an HTTP URL for Telegram to get a file from the Internet, or pass "attach://<file_attach_name>" to upload a new one using multipart/form-data under <file_attach_name> name. More information on Sending Files » |
| thumbnail | String | Optional | Thumbnail of the file sent; can be ignored if thumbnail generation for the file is supported server-side. The thumbnail should be in JPEG format and less than 200 kB in size. A thumbnail's width and height should not exceed 320. Ignored if the file is not uploaded using multipart/form-data. Thumbnails can't be reused and can be only uploaded as a new file, so you can pass "attach://<file_attach_name>" if the thumbnail was uploaded using multipart/form-data under <file_attach_name>. More information on Sending Files » |
| caption | String | Optional | Caption of the audio to be sent, 0-1024 characters after entities parsing |
| parse_mode | String | Optional | Mode for parsing entities in the audio caption. See formatting options for more details. |
| caption_entities | Array of MessageEntity | Optional | List of special entities that appear in the caption, which can be specified instead of parse_mode |
| duration | Integer | Optional | Duration of the audio in seconds |
| performer | String | Optional | Performer of the audio |
| title | String | Optional | Title of the audio |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.140. InputMediaDocument

> Represents a general file to be sent

Represents a general file to be sent.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| type | String | Always | Type of the media, must be document |
| media | String | Always | File to send. Pass a file_id to send a file that exists on the Telegram servers (recommended), pass an HTTP URL for Telegram to get a file from the Internet, or pass "attach://<file_attach_name>" to upload a new one using multipart/form-data under <file_attach_name> name. More information on Sending Files » |
| thumbnail | String | Optional | Thumbnail of the file sent; can be ignored if thumbnail generation for the file is supported server-side. The thumbnail should be in JPEG format and less than 200 kB in size. A thumbnail's width and height should not exceed 320. Ignored if the file is not uploaded using multipart/form-data. Thumbnails can't be reused and can be only uploaded as a new file, so you can pass "attach://<file_attach_name>" if the thumbnail was uploaded using multipart/form-data under <file_attach_name>. More information on Sending Files » |
| caption | String | Optional | Caption of the document to be sent, 0-1024 characters after entities parsing |
| parse_mode | String | Optional | Mode for parsing entities in the document caption. See formatting options for more details. |
| caption_entities | Array of MessageEntity | Optional | List of special entities that appear in the caption, which can be specified instead of parse_mode |
| disable_content_type_detection | Boolean | Optional | Disables automatic server-side content type detection for files uploaded using multipart/form-data. Always True, if the document is sent as part of an album. |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.141. InputMediaLink

> Represents an HTTP link to be sent

Represents an HTTP link to be sent.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| type | String | Always | Type of the media, must be link |
| url | String | Always | HTTP URL of the link |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.142. InputMediaLivePhoto

> Represents a live photo to be sent

Represents a live photo to be sent.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| type | String | Always | Type of the media, must be live_photo |
| media | String | Always | Video of the live photo to send. Pass a file_id to send a file that exists on the Telegram servers (recommended) or pass "attach://<file_attach_name>" to upload a new one using multipart/form-data under <file_attach_name> name. More information on Sending Files ». Sending live photos by a URL is currently unsupported. |
| photo | String | Always | The static photo to send. Pass a file_id to send a file that exists on the Telegram servers (recommended) or pass "attach://<file_attach_name>" to upload a new one using multipart/form-data under <file_attach_name> name. More information on Sending Files ». Sending live photos by a URL is currently unsupported. |
| caption | String | Optional | Caption of the live photo to be sent, 0-1024 characters after entities parsing |
| parse_mode | String | Optional | Mode for parsing entities in the live photo caption. See formatting options for more details. |
| caption_entities | Array of MessageEntity | Optional | List of special entities that appear in the caption, which can be specified instead of parse_mode |
| show_caption_above_media | Boolean | Optional | Pass True if the caption must be shown above the message media |
| has_spoiler | Boolean | Optional | Pass True if the live photo needs to be covered with a spoiler animation |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.143. InputMediaLocation

> Represents a location to be sent

Represents a location to be sent.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| type | String | Always | Type of the media, must be location |
| latitude | Float | Always | Latitude of the location |
| longitude | Float | Always | Longitude of the location |
| horizontal_accuracy | Float | Optional | The radius of uncertainty for the location, measured in meters; 0-1500 |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.144. InputMediaPhoto

> Represents a photo to be sent

Represents a photo to be sent.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| type | String | Always | Type of the media, must be photo |
| media | String | Always | File to send. Pass a file_id to send a file that exists on the Telegram servers (recommended), pass an HTTP URL for Telegram to get a file from the Internet, or pass "attach://<file_attach_name>" to upload a new one using multipart/form-data under <file_attach_name> name. More information on Sending Files » |
| caption | String | Optional | Caption of the photo to be sent, 0-1024 characters after entities parsing |
| parse_mode | String | Optional | Mode for parsing entities in the photo caption. See formatting options for more details. |
| caption_entities | Array of MessageEntity | Optional | List of special entities that appear in the caption, which can be specified instead of parse_mode |
| show_caption_above_media | Boolean | Optional | Pass True if the caption must be shown above the message media |
| has_spoiler | Boolean | Optional | Pass True if the photo needs to be covered with a spoiler animation |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.145. InputMediaSticker

> Represents a sticker file to be sent

Represents a sticker file to be sent.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| type | String | Always | Type of the media, must be sticker |
| media | String | Always | File to send. Pass a file_id to send a file that exists on the Telegram servers (recommended), pass an HTTP URL for Telegram to get a .WEBP sticker from the Internet, or pass "attach://<file_attach_name>" to upload a new .WEBP, .TGS, or .WEBM sticker using multipart/form-data under <file_attach_name> name. More information on Sending Files » |
| emoji | String | Optional | Emoji associated with the sticker; only for just uploaded stickers |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.146. InputMediaVenue

> Represents a venue to be sent

Represents a venue to be sent.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| type | String | Always | Type of the media, must be venue |
| latitude | Float | Always | Latitude of the location |
| longitude | Float | Always | Longitude of the location |
| title | String | Always | Name of the venue |
| address | String | Always | Address of the venue |
| foursquare_id | String | Optional | Foursquare identifier of the venue |
| foursquare_type | String | Optional | Foursquare type of the venue, if known. (For example, "arts_entertainment/default", "arts_entertainment/aquarium" or "food/icecream".) |
| google_place_id | String | Optional | Google Places identifier of the venue |
| google_place_type | String | Optional | Google Places type of the venue. (See supported types.) |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.147. InputMediaVideo

> Represents a video to be sent

Represents a video to be sent.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| type | String | Always | Type of the media, must be video |
| media | String | Always | File to send. Pass a file_id to send a file that exists on the Telegram servers (recommended), pass an HTTP URL for Telegram to get a file from the Internet, or pass "attach://<file_attach_name>" to upload a new one using multipart/form-data under <file_attach_name> name. More information on Sending Files » |
| thumbnail | String | Optional | Thumbnail of the file sent; can be ignored if thumbnail generation for the file is supported server-side. The thumbnail should be in JPEG format and less than 200 kB in size. A thumbnail's width and height should not exceed 320. Ignored if the file is not uploaded using multipart/form-data. Thumbnails can't be reused and can be only uploaded as a new file, so you can pass "attach://<file_attach_name>" if the thumbnail was uploaded using multipart/form-data under <file_attach_name>. More information on Sending Files » |
| cover | String | Optional | Cover for the video in the message. Pass a file_id to send a file that exists on the Telegram servers (recommended), pass an HTTP URL for Telegram to get a file from the Internet, or pass "attach://<file_attach_name>" to upload a new one using multipart/form-data under <file_attach_name> name. More information on Sending Files » |
| start_timestamp | Integer | Optional | Start timestamp for the video in the message |
| caption | String | Optional | Caption of the video to be sent, 0-1024 characters after entities parsing |
| parse_mode | String | Optional | Mode for parsing entities in the video caption. See formatting options for more details. |
| caption_entities | Array of MessageEntity | Optional | List of special entities that appear in the caption, which can be specified instead of parse_mode |
| show_caption_above_media | Boolean | Optional | Pass True if the caption must be shown above the message media |
| width | Integer | Optional | Video width |
| height | Integer | Optional | Video height |
| duration | Integer | Optional | Video duration in seconds |
| supports_streaming | Boolean | Optional | Pass True if the uploaded video is suitable for streaming |
| has_spoiler | Boolean | Optional | Pass True if the video needs to be covered with a spoiler animation |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.148. InputMediaVoiceNote

> Represents a voice message file to be sent

Represents a voice message file to be sent.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| type | String | Always | Type of the media, must be voice_note |
| media | String | Always | File to send. Pass a file_id to send a file that exists on the Telegram servers (recommended), pass an HTTP URL for Telegram to get a file from the Internet, or pass "attach://" to upload a new one using multipart/form-data under  name. More information on Sending Files » |
| caption | String | Optional | Caption of the voice message to be sent, 0-1024 characters after entities parsing |
| parse_mode | String | Optional | Mode for parsing entities in the voice message caption. See formatting options for more details. |
| caption_entities | Array of MessageEntity | Optional | List of special entities that appear in the caption, which can be specified instead of parse_mode |
| duration | Integer | Optional | Duration of the voice message in seconds |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.149. InputMessageContent

> This object represents the content of a message to be sent as a result of an inline query

This object represents the content of a message to be sent as a result of an inline query. Telegram clients currently support the following types:

* InputTextMessageContent

* InputRichMessageContent

* InputLocationMessageContent

* InputVenueMessageContent

* InputContactMessageContent

* InputInvoiceMessageContent

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.150. InputPaidMedia

> This object describes the paid media to be sent

This object describes the paid media to be sent. Currently, it can be one of

* InputPaidMediaLivePhoto

* InputPaidMediaPhoto

* InputPaidMediaVideo

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.151. InputPaidMediaLivePhoto

> The paid media to send is a live photo

The paid media to send is a live photo.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| type | String | Always | Type of the media, must be live_photo |
| media | String | Always | Video of the live photo to send. Pass a file_id to send a file that exists on the Telegram servers (recommended) or pass "attach://<file_attach_name>" to upload a new one using multipart/form-data under <file_attach_name> name. More information on Sending Files ». Sending live photos by a URL is currently unsupported. |
| photo | String | Always | The static photo to send. Pass a file_id to send a file that exists on the Telegram servers (recommended) or pass "attach://<file_attach_name>" to upload a new one using multipart/form-data under <file_attach_name> name. More information on Sending Files ». Sending live photos by a URL is currently unsupported. |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.152. InputPaidMediaPhoto

> The paid media to send is a photo

The paid media to send is a photo.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| type | String | Always | Type of the media, must be photo |
| media | String | Always | File to send. Pass a file_id to send a file that exists on the Telegram servers (recommended), pass an HTTP URL for Telegram to get a file from the Internet, or pass "attach://<file_attach_name>" to upload a new one using multipart/form-data under <file_attach_name> name. More information on Sending Files » |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.153. InputPaidMediaVideo

> The paid media to send is a video

The paid media to send is a video.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| type | String | Always | Type of the media, must be video |
| media | String | Always | File to send. Pass a file_id to send a file that exists on the Telegram servers (recommended), pass an HTTP URL for Telegram to get a file from the Internet, or pass "attach://<file_attach_name>" to upload a new one using multipart/form-data under <file_attach_name> name. More information on Sending Files » |
| thumbnail | String | Optional | Thumbnail of the file sent; can be ignored if thumbnail generation for the file is supported server-side. The thumbnail should be in JPEG format and less than 200 kB in size. A thumbnail's width and height should not exceed 320. Ignored if the file is not uploaded using multipart/form-data. Thumbnails can't be reused and can be only uploaded as a new file, so you can pass "attach://<file_attach_name>" if the thumbnail was uploaded using multipart/form-data under <file_attach_name>. More information on Sending Files » |
| cover | String | Optional | Cover for the video in the message. Pass a file_id to send a file that exists on the Telegram servers (recommended), pass an HTTP URL for Telegram to get a file from the Internet, or pass "attach://<file_attach_name>" to upload a new one using multipart/form-data under <file_attach_name> name. More information on Sending Files » |
| start_timestamp | Integer | Optional | Start timestamp for the video in the message |
| width | Integer | Optional | Video width |
| height | Integer | Optional | Video height |
| duration | Integer | Optional | Video duration in seconds |
| supports_streaming | Boolean | Optional | Pass True if the uploaded video is suitable for streaming |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.154. InputPollMedia

> This object represents the content of a poll description or a quiz explanation to be sent

This object represents the content of a poll description or a quiz explanation to be sent. It should be one of

* InputMediaAnimation

* InputMediaAudio

* InputMediaDocument

* InputMediaLivePhoto

* InputMediaLocation

* InputMediaPhoto

* InputMediaVenue

* InputMediaVideo

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.155. InputPollOption

> This object contains information about one answer option in a poll to be sent

This object contains information about one answer option in a poll to be sent.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| text | String | Always | Option text, 1-100 characters |
| text_parse_mode | String | Optional | Mode for parsing entities in the text. See formatting options for more details. Currently, only custom emoji entities are allowed. |
| text_entities | Array of MessageEntity | Optional | A JSON-serialized list of special entities that appear in the poll option text. It can be specified instead of text_parse_mode. |
| media | InputPollOptionMedia | Optional | Media added to the poll option |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.156. InputPollOptionMedia

> This object represents the content of a poll option to be sent

This object represents the content of a poll option to be sent. It should be one of

* InputMediaAnimation

* InputMediaLink

* InputMediaLivePhoto

* InputMediaLocation

* InputMediaPhoto

* InputMediaSticker

* InputMediaVenue

* InputMediaVideo

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.157. InputProfilePhoto

> This object describes a profile photo to set

This object describes a profile photo to set. Currently, it can be one of

* InputProfilePhotoStatic

* InputProfilePhotoAnimated

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.158. InputProfilePhotoAnimated

> An animated profile photo in the MPEG4 format

An animated profile photo in the MPEG4 format.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| type | String | Always | Type of the profile photo, must be animated |
| animation | String | Always | The animated profile photo. Profile photos can't be reused and can only be uploaded as a new file, so you can pass "attach://<file_attach_name>" if the photo was uploaded using multipart/form-data under <file_attach_name>. More information on Sending Files » |
| main_frame_timestamp | Float | Optional | Timestamp in seconds of the frame that will be used as the static profile photo. Defaults to 0.0. |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.159. InputProfilePhotoStatic

> A static profile photo in the .JPG format

A static profile photo in the .JPG format.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| type | String | Always | Type of the profile photo, must be static |
| photo | String | Always | The static profile photo. Profile photos can't be reused and can only be uploaded as a new file, so you can pass "attach://<file_attach_name>" if the photo was uploaded using multipart/form-data under <file_attach_name>. More information on Sending Files » |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.160. Rich Messages: Complete Guide

> Build fully formatted Telegram messages with blocks, HTML or Markdown: InputRichMessage, the block catalog, inline RichText styling, media layouts and limits.

**Rich Messages** are fully formatted Telegram messages built from *blocks* — paragraphs, headings, lists, tables, collages, slideshows, quotations, media and more. They go far beyond plain `parse_mode` text: one message can mix media, structured layout, and inline text styling, similar to an HTML page.

- Send them with [sendRichMessage](/sendrichmessage) (drafts with [sendRichMessageDraft](/sendrichmessagedraft)).

- A sent rich message is returned as a [RichMessage](/richmessage) object containing its `blocks`.

- Rich messages can also be edited ephemerally with [editEphemeralMessageText](/editephemeralmessagetext), [editEphemeralMessageMedia](/editephemeralmessagemedia) and related methods.

#### Two Ways to Build a Rich Message

The [InputRichMessage](/inputrichmessage) object supports three interchangeable content modes:

| Field | Type | Description |
| --- | --- | --- |
| blocks | Array of InputRichBlock | Structured content as a list of block objects — full control over layout |
| html | String | Content described with rich-message HTML formatting |
| markdown | String | Content described with rich-message Markdown formatting |
| media | Array of InputRichMessageMedia | Media used by tg://photo?id=, tg://video?id=, tg://document?id= and tg://audio?id= links |
| is_rtl | Boolean | Show the message right-to-left |
| skip_entity_detection | Boolean | Disable automatic detection of URLs, mentions, hashtags, etc. |

#### Quick Start (HTML & Markdown Mode)

For simple rich content, pass an HTML or Markdown string directly — Telegram renders it into blocks automatically:

```php

```

#### Structured Blocks Mode

For precise layout, compose the message from typed blocks. Every block carries a `type` field; each type is documented on its own page in the list below. A simple example with one text paragraph containing bold inline text:

```php
{
  "blocks": [
    {
      "type": "paragraph",
      "text": { "type": "bold", "text": "Hello from Botlify Cloud!" }
    }
  ]
}
```

#### Block Catalog

Layout blocks (each page documents the exact fields):

| Group | Blocks |
| --- | --- |
| Text | RichBlockParagraph, RichBlockSectionHeading, RichBlockDivider, RichBlockFooter |
| Quotations | RichBlockBlockQuotation, RichBlockExpandableBlockQuotation, RichBlockPullQuotation, RichBlockThinking |
| Lists & Tables | RichBlockList, RichBlockListItem, RichBlockTable, RichBlockTableCell |
| Media Layouts | RichBlockCollage, RichBlockSlideshow, RichBlockPhoto, RichBlockVideo, RichBlockAudio, RichBlockVoiceNote, RichBlockDocument, RichBlockAnimation, RichBlockMap |
| Interactive | RichBlockButtons, RichMessageButton, RichBlockAnchor, RichBlockDetails |

#### Inline Text Styling (RichText)

Inside text blocks, the [RichText](/richtext) family styles spans of text: [bold](/richtextbold), [italic](/richtextitalic), [underline](/richtextunderline), [strikethrough](/richtextstrikethrough), [spoiler](/richtextspoiler), [code](/richtextcode), [subscript](/richtextsubscript), [superscript](/richtextsuperscript), [datetime](/richtextdatetime), [custom emoji](/richtextcustomemoji), [math expressions](/richtextmathematicalexpression), and auto-detected entities like [URLs](/richtexturl), [mentions](/richtextmention), [hashtags](/richtexthashtag), [emails](/richtextemailaddress), [phone numbers](/richtextphonenumber), [bot commands](/richtextbotcommand), [cashtags](/richtextcashtag) and [bank card numbers](/richtextbankcardnumber).

#### Limits

Rich messages have dedicated size and content limits. See the official [Rich Message Limits](https://core.telegram.org/bots/api#rich-message-limits) section, and the [RichMessage](/richmessage) / [RichBlock](/richblock) reference pages for the returned objects.

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.161. inputrichblock

> This object represents a block in a rich formatted message to be sent

This object represents a block in a rich formatted message to be sent. Currently, it can be any of the following types:

* InputRichBlockParagraph

* InputRichBlockSectionHeading

* InputRichBlockPreformatted

* InputRichBlockFooter

* InputRichBlockDivider

* InputRichBlockMathematicalExpression

* InputRichBlockAnchor

* InputRichBlockList

* InputRichBlockBlockQuotation

* InputRichBlockExpandableBlockQuotation

* InputRichBlockPullQuotation

* InputRichBlockCollage

* InputRichBlockSlideshow

* InputRichBlockTable

* InputRichBlockDetails

* InputRichBlockMap

* InputRichBlockButtons

* InputRichBlockAnimation

* InputRichBlockAudio

* InputRichBlockDocument

* InputRichBlockPhoto

* InputRichBlockVideo

* InputRichBlockVoiceNote

* InputRichBlockThinking

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.162. inputrichblockanchor

> A block with an anchor, corresponding to the HTML tag <a> with the attribute name

A block with an anchor, corresponding to the HTML tag `<a>` with the attribute `name`.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| type | String | Always | Type of the block, always "anchor" |
| name | String | Always | The name of the anchor |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.163. inputrichblockanimation

> A block with an animation, corresponding to the HTML tag <video>

A block with an animation, corresponding to the HTML tag `<video>`.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| type | String | Always | Type of the block, always "animation" |
| animation | InputMediaAnimation | Always | The animation. Caption is ignored. |
| caption | RichBlockCaption | Optional | Caption of the block |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.164. inputrichblockaudio

> A block with a music file, corresponding to the HTML tag <audio>

A block with a music file, corresponding to the HTML tag `<audio>`.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| type | String | Always | Type of the block, always "audio" |
| audio | InputMediaAudio | Always | The audio. Caption is ignored. |
| caption | RichBlockCaption | Optional | Caption of the block |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.165. inputrichblockblockquotation

> A block quotation, corresponding to the HTML tag <blockquote>

A block quotation, corresponding to the HTML tag `<blockquote>`.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| type | String | Always | Type of the block, always "blockquote" |
| blocks | Array of InputRichBlock | Always | Content of the block |
| credit | RichText | Optional | Credit of the block |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.166. inputrichblockbuttons

> A block containing a list of buttons that are shown in one row, corresponding to the custom HTML tag <tg-button-row>

A block containing a list of buttons that are shown in one row, corresponding to the custom HTML tag `<tg-button-row>`.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| type | String | Always | Type of the block, always "buttons" |
| buttons | Array of RichMessageButton | Always | List of 1-8 buttons to send |
| align | String | Optional | Horizontal alignment of the buttons. Currently, must be one of "left", "center", or "right". |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.167. inputrichblockcollage

> A collage, corresponding to the custom HTML tag <tg-collage>

A collage, corresponding to the custom HTML tag `<tg-collage>`.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| type | String | Always | Type of the block, always "collage" |
| blocks | Array of InputRichBlock | Always | Elements of the collage |
| caption | RichBlockCaption | Optional | Caption of the block |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.168. inputrichblockdetails

> An expandable block for details disclosure, corresponding to the HTML tag <details>

An expandable block for details disclosure, corresponding to the HTML tag `<details>`.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| type | String | Always | Type of the block, always "details" |
| summary | RichText | Always | Always shown summary of the block |
| blocks | Array of InputRichBlock | Always | Content of the block |
| is_open | True | Optional | Pass True if the content of the block is visible by default |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.169. inputrichblockdivider

> A divider, corresponding to the HTML tag <hr/>

A divider, corresponding to the HTML tag `<hr/>`.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| type | String | Always | Type of the block, always "divider" |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.170. inputrichblockdocument

> A block with a general file, corresponding to the custom HTML tag <tg-document>

A block with a general file, corresponding to the custom HTML tag `<tg-document>`.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| type | String | Always | Type of the block, always "document" |
| document | InputMediaDocument | Always | The document. Caption is ignored. |
| caption | RichBlockCaption | Optional | Caption of the block |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.171. inputrichblockexpandableblockquotation

> A block quotation, corresponding to the HTML tag <blockquote> with custom attribute "expandable"

A block quotation, corresponding to the HTML tag `<blockquote>` with custom attribute `"expandable"`.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| type | String | Always | Type of the block, always "expandable_blockquote" |
| text | RichText | Always | Content of the block |
| credit | RichText | Optional | Credit of the block |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.172. inputrichblockfooter

> A footer, corresponding to the HTML tag <footer>

A footer, corresponding to the HTML tag `<footer>`.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| type | String | Always | Type of the block, always "footer" |
| text | RichText | Always | Text of the block |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.173. inputrichblocklist

> A list of blocks, corresponding to the HTML tag <ul> or <ol> with multiple nested tags <li>

A list of blocks, corresponding to the HTML tag `<ul>` or `<ol>` with multiple nested tags `<li>`.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| type | String | Always | Type of the block, always "list" |
| items | Array of InputRichBlockListItem | Always | Items of the list |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.174. inputrichblocklistitem

> An item of a list to be sent

An item of a list to be sent.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| blocks | Array of InputRichBlock | Always | The content of the item |
| has_checkbox | True | Optional | Pass True if the item has a checkbox |
| is_checked | True | Optional | Pass True if the item has a checked checkbox |
| value | Integer | Optional | For ordered lists, the numeric value of the item label |
| type | String | Optional | For ordered lists, the type of the item label; must be one of "a" for lowercase letters, "A" for uppercase letters, "i" for lowercase Roman numerals, "I" for uppercase Roman numerals, or "1" for decimal numbers |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.175. inputrichblockmap

> A block with a map, corresponding to the custom HTML tag <tg-map>

A block with a map, corresponding to the custom HTML tag `<tg-map>`. The map's width and height must not exceed 10000 in total. The width and height ratio must be at most 20.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| type | String | Always | Type of the block, always "map" |
| location | Location | Always | Location of the center of the map |
| zoom | Integer | Optional | Map zoom level; 0-24 |
| width | Integer | Optional | Map width; 0-10000 |
| height | Integer | Optional | Map height; 0-10000 |
| caption | RichBlockCaption | Optional | Caption of the block |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.176. inputrichblockmathematicalexpression

> A block with a mathematical expression in LaTeX format, corresponding to the custom HTML tag <tg-math-block>

A block with a mathematical expression in LaTeX format, corresponding to the custom HTML tag `<tg-math-block>`.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| type | String | Always | Type of the block, always "mathematical_expression" |
| expression | String | Always | The mathematical expression in LaTeX format |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.177. inputrichblockparagraph

> A text paragraph, corresponding to the HTML tag <p>

A text paragraph, corresponding to the HTML tag `<p>`.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| type | String | Always | Type of the block, always "paragraph" |
| text | RichText | Always | Text of the block |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.178. inputrichblockphoto

> A block with a photo, corresponding to the HTML tag <img>

A block with a photo, corresponding to the HTML tag `<img>`.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| type | String | Always | Type of the block, always "photo" |
| photo | InputMediaPhoto | Always | The photo. Caption is ignored. |
| caption | RichBlockCaption | Optional | Caption of the block |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.179. inputrichblockpreformatted

> A preformatted text block, corresponding to the nested HTML tags <pre> and <code>

A preformatted text block, corresponding to the nested HTML tags `<pre>` and `<code>`.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| type | String | Always | Type of the block, always "pre" |
| text | RichText | Always | Text of the block |
| language | String | Optional | The programming language of the text |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.180. inputrichblockpullquotation

> A quotation with centered text, loosely corresponding to the HTML tag <aside>

A quotation with centered text, loosely corresponding to the HTML tag `<aside>`.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| type | String | Always | Type of the block, always "pullquote" |
| text | RichText | Always | Text of the block |
| credit | RichText | Optional | Credit of the block |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.181. inputrichblocksectionheading

> A section heading, corresponding to the HTML tags <h1>, <h2>, <h3>, <h4>, <h5>, or <h6>

A section heading, corresponding to the HTML tags `<h1>`, `<h2>`, `<h3>`, `<h4>`, `<h5>`, or `<h6>`.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| type | String | Always | Type of the block, always "heading" |
| text | RichText | Always | Text of the block |
| size | Integer | Always | Relative size of the text font; 1-6, 1 is the largest, 6 is the smallest |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.182. inputrichblockslideshow

> A slideshow, corresponding to the custom HTML tag <tg-slideshow>

A slideshow, corresponding to the custom HTML tag `<tg-slideshow>`.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| type | String | Always | Type of the block, always "slideshow" |
| blocks | Array of InputRichBlock | Always | Elements of the slideshow |
| caption | RichBlockCaption | Optional | Caption of the block |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.183. inputrichblocktable

> A table, corresponding to the HTML tag <table>

A table, corresponding to the HTML tag `<table>`.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| type | String | Always | Type of the block, always "table" |
| cells | Array of Array of RichBlockTableCell | Always | Cells of the table |
| is_bordered | True | Optional | Pass True if the table has borders |
| is_striped | True | Optional | Pass True if the table is striped |
| is_compact | True | Optional | Pass True if table cells must have smaller indents |
| caption | RichText | Optional | Caption of the table |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.184. inputrichblockthinking

> A block with a "Thinking..." placeholder, corresponding to the custom HTML tag <tg-thinking>

A block with a "Thinking..." placeholder, corresponding to the custom HTML tag `<tg-thinking>`. The block may be used only in sendRichMessageDraft, therefore it can't be received in messages. See https://t.me/addemoji/AIActions for examples of custom emoji that are recommended for usage in the block.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| type | String | Always | Type of the block, always "thinking" |
| text | RichText | Always | Text of the block. See https://t.me/addemoji/AIActions for examples of custom emoji that are recommended for usage in the block. |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.185. inputrichblockvideo

> A block with a video, corresponding to the HTML tag <video>

A block with a video, corresponding to the HTML tag `<video>`.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| type | String | Always | Type of the block, always "video" |
| video | InputMediaVideo | Always | The video. Caption is ignored. |
| caption | RichBlockCaption | Optional | Caption of the block |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.186. inputrichblockvoicenote

> A block with a voice note, corresponding to the HTML tag <audio>

A block with a voice note, corresponding to the HTML tag `<audio>`.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| type | String | Always | Type of the block, always "voice_note" |
| voice_note | InputMediaVoiceNote | Always | The voice note. Caption is ignored. |
| caption | RichBlockCaption | Optional | Caption of the block |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.187. inputrichmessage

> Describes a rich message to be sent

Describes a rich message to be sent. Exactly **one** of the fields *html*, *markdown*, or *blocks* must be used.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| blocks | Array of InputRichBlock | Optional | Content of the rich message to send described as a list of blocks |
| html | String | Optional | Content of the rich message to send described using HTML formatting. See rich message formatting options for more details. Use media field to specify the media used in the message. |
| markdown | String | Optional | Content of the rich message to send described using Markdown formatting. See rich message formatting options for more details. Use media field to specify the media used in the message. |
| media | Array of InputRichMessageMedia | Optional | List of media that are specified in the markdown or html fields using tg://photo?id=, tg://video?id=, tg://document?id=, and tg://audio?id= links |
| is_rtl | Boolean | Optional | Pass True if the rich message must be shown right-to-left |
| skip_entity_detection | Boolean | Optional | Pass True to skip automatic detection of entities (e.g., URLs, email addresses, username mentions, hashtags, cashtags, bot commands, or phone numbers) in the text |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.188. InputRichMessageContent

> Represents the content of a rich message to be sent as the result of an inline query

Represents the content of a rich message to be sent as the result of an inline query.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| rich_message | InputRichMessage | Always | The message to be sent. Only previously uploaded files may be used in the message. |

#### Example

```php
{"text": "Hello! Rich message body…", "parse_mode": "HTML"}
```

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.189. inputrichmessagemedia

> Describes a media element embedded in an outgoing rich message

Describes a media element embedded in an outgoing rich message.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| id | String | Always | Unique identifier of the media used in a tg://photo?id=, tg://video?id=, tg://document?id=, or tg://audio?id= link. 1-64 characters, only A-Z, a-z, 0-9, _ and - are allowed. |
| media | InputMediaAnimation or InputMediaAudio or InputMediaDocument or InputMediaPhoto or InputMediaVideo or InputMediaVoiceNote | Always | The media to be sent. Everything except the media itself and its properties is ignored. |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.190. InputSticker

> This object describes a sticker to be added to a sticker set

This object describes a sticker to be added to a sticker set.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| sticker | String | Always | The added sticker. Pass a file_id as a String to send a file that already exists on the Telegram servers, pass an HTTP URL as a String for Telegram to get a file from the Internet, or pass "attach://<file_attach_name>" to upload a new file using multipart/form-data under <file_attach_name> name. Animated and video stickers can't be uploaded via HTTP URL. More information on Sending Files » |
| format | String | Always | Format of the added sticker, must be one of "static" for a .WEBP or .PNG image, "animated" for a .TGS animation, "video" for a .WEBM video |
| emoji_list | Array of String | Always | List of 1-20 emoji associated with the sticker |
| mask_position | MaskPosition | Optional | Position where the mask should be placed on faces. For "mask" stickers only. |
| keywords | Array of String | Optional | List of 0-20 search keywords for the sticker with total length of up to 64 characters. For "regular" and "custom_emoji" stickers only. |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.191. InputStoryContent

> This object describes the content of a story to post

This object describes the content of a story to post. Currently, it can be one of

* InputStoryContentPhoto

* InputStoryContentVideo

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.192. InputStoryContentPhoto

> Describes a photo to post as a story

Describes a photo to post as a story.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| type | String | Always | Type of the content, must be photo |
| photo | String | Always | The photo to post as a story. The photo must be of the size 1080x1920 and must not exceed 10 MB. The photo can't be reused and can only be uploaded as a new file, so you can pass "attach://<file_attach_name>" if the photo was uploaded using multipart/form-data under <file_attach_name>. More information on Sending Files » |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.193. InputStoryContentVideo

> Describes a video to post as a story

Describes a video to post as a story.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| type | String | Always | Type of the content, must be video |
| video | String | Always | The video to post as a story. The video must be of the size 720x1280, streamable, encoded with H.265 codec, with key frames added each second in the MPEG4 format, and must not exceed 30 MB. The video can't be reused and can only be uploaded as a new file, so you can pass "attach://<file_attach_name>" if the video was uploaded using multipart/form-data under <file_attach_name>. More information on Sending Files » |
| duration | Float | Optional | Precise duration of the video in seconds; 0-60 |
| cover_frame_timestamp | Float | Optional | Timestamp in seconds of the frame that will be used as the static cover for the story. Defaults to 0.0. |
| is_animation | Boolean | Optional | Pass True if the video has no sound |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.194. InputTextMessageContent

> Represents the content of a text message to be sent as the result of an inline query

Represents the content of a text message to be sent as the result of an inline query.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| message_text | String | Always | Text of the message to be sent, 1-4096 characters |
| parse_mode | String | Optional | Mode for parsing entities in the message text. See formatting options for more details. |
| entities | Array of MessageEntity | Optional | List of special entities that appear in message text, which can be specified instead of parse_mode |
| link_preview_options | LinkPreviewOptions | Optional | Link preview generation options for the message |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.195. InputVenueMessageContent

> Represents the content of a venue message to be sent as the result of an inline query

Represents the content of a venue message to be sent as the result of an inline query.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| latitude | Float | Always | Latitude of the venue in degrees |
| longitude | Float | Always | Longitude of the venue in degrees |
| title | String | Always | Name of the venue |
| address | String | Always | Address of the venue |
| foursquare_id | String | Optional | Foursquare identifier of the venue, if known |
| foursquare_type | String | Optional | Foursquare type of the venue, if known. (For example, "arts_entertainment/default", "arts_entertainment/aquarium" or "food/icecream".) |
| google_place_id | String | Optional | Google Places identifier of the venue |
| google_place_type | String | Optional | Google Places type of the venue. (See supported types.) |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.196. Invoice

> This object contains basic information about an invoice

This object contains basic information about an invoice.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| title | String | Always | Product name |
| description | String | Always | Product description |
| start_parameter | String | Always | Unique bot deep-linking parameter that can be used to generate this invoice |
| currency | String | Always | Three-letter ISO 4217 currency code, or "XTR" for payments in Telegram Stars |
| total_amount | Integer | Always | Total price in the smallest units of the currency (integer, not float/double). For example, for a price of US$ 1.45 pass amount = 145. See the exp parameter in currencies.json, it shows the number of digits past the decimal point for each currency (2 for the majority of currencies). |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.197. KeyboardButton

> This object represents one button of the reply keyboard

This object represents one button of the reply keyboard. At most one of the fields other than *text*, *icon_custom_emoji_id*, and *style* must be used to specify the type of the button. For simple text buttons, *String* can be used instead of this object to specify the button text.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| text | String | Always | Text of the button. If none of the fields other than text, icon_custom_emoji_id, and style are used, it will be sent as a message when the button is pressed. |
| icon_custom_emoji_id | String | Optional | Unique identifier of the custom emoji shown before the text of the button. Can only be used by bots that purchased additional usernames on Fragment or in the messages directly sent by the bot to private, group and supergroup chats if the owner of the bot has a Telegram Premium subscription. |
| style | String | Optional | Style of the button. Must be one of "danger" (red), "success" (green) or "primary" (blue). If omitted, then an app-specific style is used. |
| request_users | KeyboardButtonRequestUsers | Optional | If specified, pressing the button will open a list of suitable users. Identifiers of selected users will be sent to the bot in a "users_shared" service message. Available in private chats only. |
| request_chat | KeyboardButtonRequestChat | Optional | If specified, pressing the button will open a list of suitable chats. Tapping on a chat will send its identifier to the bot in a "chat_shared" service message. Available in private chats only. |
| request_managed_bot | KeyboardButtonRequestManagedBot | Optional | If specified, pressing the button will ask the user to create and share a bot that will be managed by the current bot. Available for bots that enabled management of other bots in the @BotFather Mini App. Available in private chats only. |
| request_contact | Boolean | Optional | If True, the user's phone number will be sent as a contact when the button is pressed. Available in private chats only. |
| request_location | Boolean | Optional | If True, the user's current location will be sent when the button is pressed. Available in private chats only. |
| request_poll | KeyboardButtonPollType | Optional | If specified, the user will be asked to create a poll and send it to the bot when the button is pressed. Available in private chats only. |
| web_app | WebAppInfo | Optional | If specified, the described Web App will be launched when the button is pressed. The Web App will be able to send a "web_app_data" service message. Available in private chats only. |

#### Example

```php
{"text": "📊 My Balance", "request_contact": false, "request_location": false}
```

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.198. KeyboardButtonPollType

> This object represents type of a poll, which is allowed to be created and sent when the corresponding button is pressed

This object represents type of a poll, which is allowed to be created and sent when the corresponding button is pressed.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| type | String | Optional | If quiz is passed, the user will be allowed to create only polls in the quiz mode. If regular is passed, only regular polls will be allowed. Otherwise, the user will be allowed to create a poll of any type. |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.199. KeyboardButtonRequestChat

> This object defines the criteria used to request a suitable chat

This object defines the criteria used to request a suitable chat. Information about the selected chat will be shared with the bot when the corresponding button is pressed. The bot will be granted requested rights in the chat if appropriate. More about requesting chats ».

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| request_id | Integer | Always | Signed 32-bit identifier of the request, which will be received back in the ChatShared object. Must be unique within the message. |
| chat_is_channel | Boolean | Always | Pass True to request a channel chat, pass False to request a group or a supergroup chat |
| chat_is_forum | Boolean | Optional | Pass True to request a forum supergroup, pass False to request a non-forum chat. If not specified, no additional restrictions are applied. |
| chat_has_username | Boolean | Optional | Pass True to request a supergroup or a channel with a username, pass False to request a chat without a username. If not specified, no additional restrictions are applied. |
| chat_is_created | Boolean | Optional | Pass True to request a chat owned by the user. Otherwise, no additional restrictions are applied. |
| user_administrator_rights | ChatAdministratorRights | Optional | A JSON-serialized object listing the required administrator rights of the user in the chat. The rights must be a superset of bot_administrator_rights. If not specified, no additional restrictions are applied. |
| bot_administrator_rights | ChatAdministratorRights | Optional | A JSON-serialized object listing the required administrator rights of the bot in the chat. The rights must be a subset of user_administrator_rights. If not specified, no additional restrictions are applied. |
| bot_is_member | Boolean | Optional | Pass True to request a chat with the bot as a member. Otherwise, no additional restrictions are applied. |
| request_title | Boolean | Optional | Pass True to request the chat's title |
| request_username | Boolean | Optional | Pass True to request the chat's username |
| request_photo | Boolean | Optional | Pass True to request the chat's photo |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.200. KeyboardButtonRequestManagedBot

> This object defines the parameters for the creation of a managed bot

This object defines the parameters for the creation of a managed bot. Information about the created bot will be shared with the bot using the update *managed_bot* and a Message with the field *managed_bot_created*.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| request_id | Integer | Always | Signed 32-bit identifier of the request. Must be unique within the message. |
| suggested_name | String | Optional | Suggested name for the bot |
| suggested_username | String | Optional | Suggested username for the bot |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.201. KeyboardButtonRequestUsers

> This object defines the criteria used to request suitable users

This object defines the criteria used to request suitable users. Information about the selected users will be shared with the bot when the corresponding button is pressed. More about requesting users »

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| request_id | Integer | Always | Signed 32-bit identifier of the request that will be received back in the UsersShared object. Must be unique within the message. |
| user_is_bot | Boolean | Optional | Pass True to request bots, pass False to request regular users. If not specified, no additional restrictions are applied. |
| user_is_premium | Boolean | Optional | Pass True to request premium users, pass False to request non-premium users. If not specified, no additional restrictions are applied. |
| max_quantity | Integer | Optional | The maximum number of users to be selected; 1-10. Defaults to 1. |
| request_name | Boolean | Optional | Pass True to request the users' first and last names |
| request_username | Boolean | Optional | Pass True to request the users' usernames |
| request_photo | Boolean | Optional | Pass True to request the users' photos |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.202. LabeledPrice

> This object represents a portion of the price for goods or services

This object represents a portion of the price for goods or services.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| label | String | Always | Portion label |
| amount | Integer | Always | Price of the product in the smallest units of the currency (integer, not float/double). For example, for a price of US$ 1.45 pass amount = 145. See the exp parameter in currencies.json, it shows the number of digits past the decimal point for each currency (2 for the majority of currencies). |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.203. Link

> Represents an HTTP link

Represents an HTTP link.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| url | String | Always | URL of the link |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.204. LinkPreviewOptions

> Describes the options used for link preview generation

Describes the options used for link preview generation.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| is_disabled | Boolean | Optional | True, if the link preview is disabled |
| url | String | Optional | URL to use for the link preview. If empty, then the first URL found in the message text will be used. |
| prefer_small_media | Boolean | Optional | True, if the media in the link preview is supposed to be shrunk; ignored if the URL isn't explicitly specified or media size change isn't supported for the preview |
| prefer_large_media | Boolean | Optional | True, if the media in the link preview is supposed to be enlarged; ignored if the URL isn't explicitly specified or media size change isn't supported for the preview |
| show_above_text | Boolean | Optional | True, if the link preview must be shown above the message text; otherwise, the link preview will be shown below the message text |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.205. LivePhoto

> This object represents a live photo

This object represents a live photo.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| photo | Array of PhotoSize | Optional | Available sizes of the corresponding static photo |
| file_id | String | Always | Identifier for the video file which can be used to download or reuse the file |
| file_unique_id | String | Always | Unique identifier for the video file which is supposed to be the same over time and for different bots. Can't be used to download or reuse the file. |
| width | Integer | Always | Video width as defined by the sender |
| height | Integer | Always | Video height as defined by the sender |
| duration | Integer | Always | Duration of the video in seconds as defined by the sender |
| mime_type | String | Optional | MIME type of the file as defined by the sender |
| file_size | Integer | Optional | File size in bytes. It can be bigger than 2^31 and some programming languages may have difficulty/silent defects in interpreting it. But it has at most 52 significant bits, so a signed 64-bit integer or double-precision float type are safe for storing this value. |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.206. Location

> This object represents a point on the map

This object represents a point on the map.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| latitude | Float | Always | Latitude as defined by the sender |
| longitude | Float | Always | Longitude as defined by the sender |
| horizontal_accuracy | Float | Optional | The radius of uncertainty for the location, measured in meters; 0-1500 |
| live_period | Integer | Optional | Time relative to the message sending date, during which the location can be updated; in seconds. For active live locations only. |
| heading | Integer | Optional | The direction in which user is moving, in degrees; 1-360. For active live locations only. |
| proximity_alert_radius | Integer | Optional | The maximum distance for proximity alerts about approaching another chat member, in meters. For sent live locations only. |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.207. LocationAddress

> Describes the physical address of a location

Describes the physical address of a location.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| country_code | String | Always | The two-letter ISO 3166-1 alpha-2 country code of the country where the location is located |
| state | String | Optional | State of the location |
| city | String | Optional | City of the location |
| street | String | Optional | Street address of the location |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.208. LoginUrl

> This object represents a parameter of the inline keyboard button used to automatically authorize a user

This object represents a parameter of the inline keyboard button used to automatically authorize a user. It serves as a great replacement for the Telegram Login Widget when the user is coming from Telegram. All the user needs to do is tap/click a button and confirm that they want to log in:

<div class="blog_image_wrap">

<a href="/file/811140015/1734/8VZFkwWXalM.97872/6127fa62d8a0bf2b3c" target="_blank"><img src="/file/811140909/1631/20k1Z53eiyY.23995/c541e89b74253623d9" title="TITLE" alt="TITLE" srcset="/file/811140015/1734/8VZFkwWXalM.97872/6127fa62d8a0bf2b3c , 2x" /></a>

</div>

Sample bot: @DiscussBot

**NOTE:** You **must** always check the hash of the received data to verify the authentication and the integrity of the data as described in Checking authorization.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| url | String | Always | An HTTPS URL to be opened with user authorization data added to the query string when the button is pressed. If the user refuses to provide authorization data, the original URL without information about the user will be opened. The data added is the same as described in Receiving authorization data. |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.209. ManagedBotCreated

> This object contains information about the bot that was created to be managed by the current bot

This object contains information about the bot that was created to be managed by the current bot.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| bot | User | Always | Information about the bot. The bot's token can be fetched using the method getManagedBotToken. |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.210. ManagedBotUpdated

> This object contains information about the creation, token update, or owner update of a bot that is managed by the current bot

This object contains information about the creation, token update, or owner update of a bot that is managed by the current bot.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| user | User | Always | User that created the bot |
| bot | User | Always | Information about the bot. Token of the bot can be fetched using the method getManagedBotToken. |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.211. MaskPosition

> This object describes the position on faces where a mask should be placed by default

This object describes the position on faces where a mask should be placed by default.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| point | String | Always | The part of the face relative to which the mask should be placed. One of "forehead", "eyes", "mouth", or "chin". |
| x_shift | Float | Always | Shift by X-axis measured in widths of the mask scaled to the face size, from left to right. For example, choosing -1.0 will place mask just to the left of the default mask position. |
| y_shift | Float | Always | Shift by Y-axis measured in heights of the mask scaled to the face size, from top to bottom. For example, 1.0 will place the mask just below the default mask position. |
| scale | Float | Always | Mask scaling coefficient. For example, 2.0 means double size. |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.212. MaybeInaccessibleMessage

> This object describes a message that can be inaccessible to the bot

This object describes a message that can be inaccessible to the bot. It can be one of

* Message

* InaccessibleMessage

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.213. MenuButton

> This object describes the bot's menu button in a private chat

This object describes the bot's menu button in a private chat. It should be one of

* MenuButtonCommands

* MenuButtonWebApp

* MenuButtonDefault

If a menu button other than MenuButtonDefault is set for a private chat, then it is applied in the chat. Otherwise the default menu button is applied. By default, the menu button opens the list of bot commands.

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.214. MenuButtonCommands

> Represents a menu button, which opens the bot's list of commands

Represents a menu button, which opens the bot's list of commands.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| type | String | Always | Type of the button, must be commands |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.215. MenuButtonDefault

> Describes that no specific value for the menu button was set

Describes that no specific value for the menu button was set.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| type | String | Always | Type of the button, must be default |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.216. MenuButtonWebApp

> Represents a menu button, which launches a Web App

Represents a menu button, which launches a Web App.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| type | String | Always | Type of the button, must be web_app |
| text | String | Always | Text on the button |
| web_app | WebAppInfo | Always | Description of the Web App that will be launched when the user presses the button. The Web App will be able to send an arbitrary message on behalf of the user using the method answerWebAppQuery. Alternatively, a t.me link to a Web App of the bot can be specified in the object instead of the Web App's URL, in which case the Web App will be opened as if the user pressed the link. |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.217. Message

> This object represents a message

This object represents a message.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| message_id | Integer | Always | Unique message identifier inside this chat; 0 for ephemeral messages. In specific instances (e.g., a message containing a video sent to a big chat), the server might automatically schedule a message instead of sending it immediately. In such cases, this field will be 0 and the relevant message will be unusable until it is actually sent. |
| message_thread_id | Integer | Optional | Unique identifier of a message thread or forum topic to which the message belongs; for supergroups and private chats only |
| direct_messages_topic | DirectMessagesTopic | Optional | Information about the direct messages chat topic that contains the message |
| from | User | Optional | Sender of the message; may be empty for messages sent to channels. For backward compatibility, if the message was sent on behalf of a chat, the field contains a fake sender user in non-channel chats. |
| sender_chat | Chat | Optional | Sender of the message when sent on behalf of a chat. For example, the supergroup itself for messages sent by its anonymous administrators or a linked channel for messages automatically forwarded to the channel's discussion group. For backward compatibility, if the message was sent on behalf of a chat, the field from contains a fake sender user in non-channel chats. |
| sender_boost_count | Integer | Optional | If the sender of the message boosted the chat, the number of boosts added by the user |
| sender_business_bot | User | Optional | The bot that actually sent the message on behalf of the business account. Available only for outgoing messages sent on behalf of the connected business account. |
| sender_tag | String | Optional | Tag or custom title of the sender of the message; for supergroups only |
| receiver_user | User | Optional | For ephemeral messages, the user who received the message |
| ephemeral_message_id | Integer | Optional | For ephemeral messages, identifier of the ephemeral message inside this chat. The identifier may be reused for another ephemeral message after the message is deleted or expires. |
| date | Integer | Always | Date the message was sent in Unix time. It is always a positive number, representing a valid date. |
| guest_query_id | String | Optional | The unique identifier for the guest query. Use this identifier with the method answerGuestQuery to send a response message. If non-empty, the message belongs to the chat where the guest bot was summoned, which may not coincide with other existing bot chats sharing the same identifier. |
| business_connection_id | String | Optional | Unique identifier of the business connection from which the message was received. If non-empty, the message belongs to a chat of the corresponding business account that is independent from any potential bot chat which might share the same identifier. |
| chat | Chat | Always | Chat the message belongs to |
| forward_origin | MessageOrigin | Optional | Information about the original message for forwarded messages |
| is_topic_message | True | Optional | True, if the message is sent to a topic in a forum supergroup or a private chat with the bot |
| is_automatic_forward | True | Optional | True, if the message is a channel post that was automatically forwarded to the connected discussion group |
| reply_to_message | Message | Optional | For replies in the same chat and message thread, the original message. Note that the Message object in this field will not contain further reply_to_message fields even if it itself is a reply. If the message is a reply to an ephemeral message, then this field may be omitted. |
| external_reply | ExternalReplyInfo | Optional | Information about the message that is being replied to, which may come from another chat or forum topic |
| quote | TextQuote | Optional | For replies that quote part of the original message, the quoted part of the message |
| reply_to_story | Story | Optional | For replies to a story, the original story |
| reply_to_checklist_task_id | Integer | Optional | Identifier of the specific checklist task that is being replied to |
| reply_to_poll_option_id | String | Optional | Persistent identifier of the specific poll option that is being replied to |
| via_bot | User | Optional | Bot through which the message was sent |
| guest_bot_caller_user | User | Optional | For a message sent by a guest bot, this is the user whose original message triggered the bot's response |
| guest_bot_caller_chat | Chat | Optional | For a message sent by a guest bot, this is the chat whose original message triggered the bot's response |
| edit_date | Integer | Optional | Date the message was last edited in Unix time |
| has_protected_content | True | Optional | True, if the message can't be forwarded |
| is_from_offline | True | Optional | True, if the message was sent by an implicit action, for example, as an away or a greeting business message, or as a scheduled message |
| is_paid_post | True | Optional | True, if the message is a paid post. Note that such posts must not be deleted for 24 hours to receive the payment and can't be edited. |
| media_group_id | String | Optional | The unique identifier inside this chat of a media message group this message belongs to |
| author_signature | String | Optional | Signature of the post author for messages in channels, or the custom title of an anonymous group administrator |
| paid_star_count | Integer | Optional | The number of Telegram Stars that were paid by the sender of the message to send it |
| text | String | Optional | For text messages, the actual UTF-8 text of the message |
| entities | Array of MessageEntity | Optional | For text messages, special entities like usernames, URLs, bot commands, etc. that appear in the text |
| link_preview_options | LinkPreviewOptions | Optional | Options used for link preview generation for the message, if it is a text message and link preview options were changed |
| suggested_post_info | SuggestedPostInfo | Optional | Information about suggested post parameters if the message is a suggested post in a channel direct messages chat. If the message is an approved or declined suggested post, then it can't be edited. |
| effect_id | String | Optional | Unique identifier of the message effect added to the message |
| rich_message | RichMessage | Optional | Message is a rich formatted message |
| animation | Animation | Optional | Message is an animation, information about the animation. For backward compatibility, when this field is set, the document field will also be set. |
| audio | Audio | Optional | Message is an audio file, information about the file |
| document | Document | Optional | Message is a general file, information about the file |
| live_photo | LivePhoto | Optional | Message is a live photo, information about the live photo. For backward compatibility, when this field is set, the photo field will also be set. |
| paid_media | PaidMediaInfo | Optional | Message contains paid media; information about the paid media |
| photo | Array of PhotoSize | Optional | Message is a photo, available sizes of the photo |
| sticker | Sticker | Optional | Message is a sticker, information about the sticker |
| story | Story | Optional | Message is a forwarded story |
| video | Video | Optional | Message is a video, information about the video |
| video_note | VideoNote | Optional | Message is a video note, information about the video message |
| voice | Voice | Optional | Message is a voice message, information about the file |
| caption | String | Optional | Caption for the animation, audio, document, paid media, photo, video or voice |
| caption_entities | Array of MessageEntity | Optional | For messages with a caption, special entities like usernames, URLs, bot commands, etc. that appear in the caption |
| show_caption_above_media | True | Optional | True, if the caption must be shown above the message media |
| has_media_spoiler | True | Optional | True, if the message media is covered by a spoiler animation |
| checklist | Checklist | Optional | Message is a checklist |
| contact | Contact | Optional | Message is a shared contact, information about the contact |
| dice | Dice | Optional | Message is a dice with random value |
| game | Game | Optional | Message is a game, information about the game. More about games » |
| poll | Poll | Optional | Message is a native poll, information about the poll |
| venue | Venue | Optional | Message is a venue, information about the venue. For backward compatibility, when this field is set, the location field will also be set. |
| location | Location | Optional | Message is a shared location, information about the location |
| new_chat_members | Array of User | Optional | New members that were added to the group or supergroup and information about them (the bot itself may be one of these members) |
| left_chat_member | User | Optional | A member was removed from the group, information about them (this member may be the bot itself) |
| chat_owner_left | ChatOwnerLeft | Optional | Service message: chat owner has left |
| chat_owner_changed | ChatOwnerChanged | Optional | Service message: chat owner has changed |
| new_chat_title | String | Optional | A chat title was changed to this value |
| new_chat_photo | Array of PhotoSize | Optional | A chat photo was change to this value |
| delete_chat_photo | True | Optional | Service message: the chat photo was deleted |
| group_chat_created | True | Optional | Service message: the group has been created |
| supergroup_chat_created | True | Optional | Service message: the supergroup has been created. This field can't be received in a message coming through updates, because bot can't be a member of a supergroup when it is created. It can only be found in reply_to_message if someone replies to a very first message in a directly created supergroup. |
| channel_chat_created | True | Optional | Service message: the channel has been created. This field can't be received in a message coming through updates, because bot can't be a member of a channel when it is created. It can only be found in reply_to_message if someone replies to a very first message in a channel. |
| message_auto_delete_timer_changed | MessageAutoDeleteTimerChanged | Optional | Service message: auto-delete timer settings changed in the chat |
| migrate_to_chat_id | Integer | Optional | The group has been migrated to a supergroup with the specified identifier. This number may have more than 32 significant bits and some programming languages may have difficulty/silent defects in interpreting it. But it has at most 52 significant bits, so a signed 64-bit integer or double-precision float type are safe for storing this identifier. |
| migrate_from_chat_id | Integer | Optional | The supergroup has been migrated from a group with the specified identifier. This number may have more than 32 significant bits and some programming languages may have difficulty/silent defects in interpreting it. But it has at most 52 significant bits, so a signed 64-bit integer or double-precision float type are safe for storing this identifier. |
| pinned_message | MaybeInaccessibleMessage | Optional | Specified message was pinned. Note that the Message object in this field will not contain further reply_to_message fields even if it itself is a reply. |
| invoice | Invoice | Optional | Message is an invoice for a payment, information about the invoice. More about payments » |
| successful_payment | SuccessfulPayment | Optional | Message is a service message about a successful payment, information about the payment. More about payments » |
| refunded_payment | RefundedPayment | Optional | Message is a service message about a refunded payment, information about the payment. More about payments » |
| users_shared | UsersShared | Optional | Service message: users were shared with the bot |
| chat_shared | ChatShared | Optional | Service message: a chat was shared with the bot |
| gift | GiftInfo | Optional | Service message: a regular gift was sent or received |
| unique_gift | UniqueGiftInfo | Optional | Service message: a unique gift was sent or received |
| gift_upgrade_sent | GiftInfo | Optional | Service message: upgrade of a gift was purchased after the gift was sent |
| connected_website | String | Optional | The domain name of the website on which the user has logged in. More about Telegram Login » |
| write_access_allowed | WriteAccessAllowed | Optional | Service message: the user allowed the bot to write messages after adding it to the attachment or side menu, launching a Web App from a link, or accepting an explicit request from a Web App sent by the method requestWriteAccess |
| passport_data | PassportData | Optional | Telegram Passport data |
| proximity_alert_triggered | ProximityAlertTriggered | Optional | Service message: a user in the chat triggered another user's proximity alert while sharing Live Location |
| boost_added | ChatBoostAdded | Optional | Service message: user boosted the chat |
| chat_background_set | ChatBackground | Optional | Service message: chat background set |
| checklist_tasks_done | ChecklistTasksDone | Optional | Service message: some tasks in a checklist were marked as done or not done |
| checklist_tasks_added | ChecklistTasksAdded | Optional | Service message: tasks were added to a checklist |
| community_chat_added | CommunityChatAdded | Optional | Service message: chat or bot added to a Community |
| community_chat_joined | CommunityChatJoined | Optional | Service message: chat was joined by a user from a Community |
| community_chat_removed | CommunityChatRemoved | Optional | Service message: chat or bot removed from a Community |
| direct_message_price_changed | DirectMessagePriceChanged | Optional | Service message: the price for paid messages in the corresponding direct messages chat of a channel has changed |
| forum_topic_created | ForumTopicCreated | Optional | Service message: forum topic created |
| forum_topic_edited | ForumTopicEdited | Optional | Service message: forum topic edited |
| forum_topic_closed | ForumTopicClosed | Optional | Service message: forum topic closed |
| forum_topic_reopened | ForumTopicReopened | Optional | Service message: forum topic reopened |
| general_forum_topic_hidden | GeneralForumTopicHidden | Optional | Service message: the 'General' forum topic hidden |
| general_forum_topic_unhidden | GeneralForumTopicUnhidden | Optional | Service message: the 'General' forum topic unhidden |
| giveaway_created | GiveawayCreated | Optional | Service message: a scheduled giveaway was created |
| giveaway | Giveaway | Optional | The message is a scheduled giveaway message |
| giveaway_winners | GiveawayWinners | Optional | A giveaway with public winners was completed |
| giveaway_completed | GiveawayCompleted | Optional | Service message: a giveaway without public winners was completed |
| managed_bot_created | ManagedBotCreated | Optional | Service message: user created a bot that will be managed by the current bot |
| paid_message_price_changed | PaidMessagePriceChanged | Optional | Service message: the price for paid messages has changed in the chat |
| poll_option_added | PollOptionAdded | Optional | Service message: answer option was added to a poll |
| poll_option_deleted | PollOptionDeleted | Optional | Service message: answer option was deleted from a poll |
| suggested_post_approved | SuggestedPostApproved | Optional | Service message: a suggested post was approved |
| suggested_post_approval_failed | SuggestedPostApprovalFailed | Optional | Service message: approval of a suggested post has failed |
| suggested_post_declined | SuggestedPostDeclined | Optional | Service message: a suggested post was declined |
| suggested_post_paid | SuggestedPostPaid | Optional | Service message: payment for a suggested post was received |
| suggested_post_refunded | SuggestedPostRefunded | Optional | Service message: payment for a suggested post was refunded |
| video_chat_scheduled | VideoChatScheduled | Optional | Service message: video chat scheduled |
| video_chat_started | VideoChatStarted | Optional | Service message: video chat started |
| video_chat_ended | VideoChatEnded | Optional | Service message: video chat ended |
| video_chat_participants_invited | VideoChatParticipantsInvited | Optional | Service message: new participants invited to a video chat |
| web_app_data | WebAppData | Optional | Service message: data sent by a Web App |
| reply_markup | InlineKeyboardMarkup | Optional | Inline keyboard attached to the message. login_url buttons are represented as ordinary url buttons. |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.218. MessageAutoDeleteTimerChanged

> This object represents a service message about a change in auto-delete timer settings

This object represents a service message about a change in auto-delete timer settings.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| message_auto_delete_time | Integer | Always | New auto-delete time for messages in the chat; in seconds |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.219. MessageEntity

> This object represents one special entity in a text message

This object represents one special entity in a text message. For example, hashtags, usernames, URLs, etc.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| type | String | Always | Type of the entity. Currently, can be "mention" (@username), "hashtag" (#hashtag or #hashtag@chatusername), "cashtag" ($USD or $USD@chatusername), "bot_command" (/start@jobs_bot), "url" (https://telegram.org), "email" (do-not-reply@telegram.org), "phone_number" (+1-212-555-0123), "bold" (bold text), "italic" (italic text), "underline" (underlined text), "strikethrough" (strikethrough text), "spoiler" (spoiler message), "blockquote" (block quotation), "expandable_blockquote" (collapsed-by-default block quotation), "code" (monowidth string), "pre" (monowidth block), "text_link" (for clickable text URLs), "text_mention" (for users without usernames), "custom_emoji" (for inline custom emoji stickers), or "date_time" (for formatted date and time). |
| offset | Integer | Always | Offset in UTF-16 code units to the start of the entity |
| length | Integer | Always | Length of the entity in UTF-16 code units |
| url | String | Optional | For "text_link" only, URL that will be opened after user taps on the text |
| user | User | Optional | For "text_mention" only, the mentioned user |
| language | String | Optional | For "pre" only, the programming language of the entity text |
| custom_emoji_id | String | Optional | For "custom_emoji" only, unique identifier of the custom emoji. Use getCustomEmojiStickers to get full information about the sticker. |
| unix_time | Integer | Optional | For "date_time" only, the Unix time associated with the entity |
| date_time_format | String | Optional | For "date_time" only, the string that defines the formatting of the date and time. See date-time entity formatting for more details. |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.220. MessageGenerationStopped

> This object describes an update about a user stopping message generation

This object describes an update about a user stopping message generation.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| chat | Chat | Always | Chat in which the message is generated |
| message_thread_id | Integer | Optional | Unique identifier of the message thread in which the message is generated |
| draft_id | Integer | Always | Unique identifier of the message draft which was stopped |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.221. MessageId

> This object represents a unique message identifier

This object represents a unique message identifier.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| message_id | Integer | Always | Unique message identifier. In specific instances (e.g., message containing a video sent to a big chat), the server might automatically schedule a message instead of sending it immediately. In such cases, this field will be 0 and the relevant message will be unusable until it is actually sent. |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.222. MessageOrigin

> This object describes the origin of a message

This object describes the origin of a message. It can be one of

* MessageOriginUser

* MessageOriginHiddenUser

* MessageOriginChat

* MessageOriginChannel

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.223. MessageOriginChannel

> The message was originally sent to a channel chat

The message was originally sent to a channel chat.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| type | String | Always | Type of the message origin, always "channel" |
| date | Integer | Always | Date the message was sent originally in Unix time |
| chat | Chat | Always | Channel chat to which the message was originally sent |
| message_id | Integer | Always | Unique message identifier inside the chat |
| author_signature | String | Optional | Signature of the original post author |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.224. MessageOriginChat

> The message was originally sent on behalf of a chat to a group chat

The message was originally sent on behalf of a chat to a group chat.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| type | String | Always | Type of the message origin, always "chat" |
| date | Integer | Always | Date the message was sent originally in Unix time |
| sender_chat | Chat | Always | Chat that sent the message originally |
| author_signature | String | Optional | For messages originally sent by an anonymous chat administrator, original message author signature |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.225. MessageOriginHiddenUser

> The message was originally sent by an unknown user

The message was originally sent by an unknown user.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| type | String | Always | Type of the message origin, always "hidden_user" |
| date | Integer | Always | Date the message was sent originally in Unix time |
| sender_user_name | String | Always | Name of the user that sent the message originally |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.226. MessageOriginUser

> The message was originally sent by a known user

The message was originally sent by a known user.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| type | String | Always | Type of the message origin, always "user" |
| date | Integer | Always | Date the message was sent originally in Unix time |
| sender_user | User | Always | User that sent the message originally |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.227. MessageReactionCountUpdated

> This object represents reaction changes on a message with anonymous reactions

This object represents reaction changes on a message with anonymous reactions.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| chat | Chat | Always | The chat containing the message |
| message_id | Integer | Always | Unique message identifier inside the chat |
| date | Integer | Always | Date of the change in Unix time |
| reactions | Array of ReactionCount | Always | List of reactions that are present on the message |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.228. MessageReactionUpdated

> This object represents a change of a reaction on a message performed by a user

This object represents a change of a reaction on a message performed by a user.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| chat | Chat | Always | The chat containing the message the user reacted to |
| message_id | Integer | Always | Unique identifier of the message inside the chat |
| user | User | Optional | The user that changed the reaction, if the user isn't anonymous |
| actor_chat | Chat | Optional | The chat on behalf of which the reaction was changed, if the user is anonymous |
| date | Integer | Always | Date of the change in Unix time |
| old_reaction | Array of ReactionType | Always | Previous list of reaction types that were set by the user |
| new_reaction | Array of ReactionType | Always | New list of reaction types that have been set by the user |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.229. OrderInfo

> This object represents information about an order

This object represents information about an order.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| name | String | Optional | User name |
| phone_number | String | Optional | User's phone number |
| email | String | Optional | User email |
| shipping_address | ShippingAddress | Optional | User shipping address |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.230. OwnedGift

> This object describes a gift received and owned by a user or a chat

This object describes a gift received and owned by a user or a chat. Currently, it can be one of

* OwnedGiftRegular

* OwnedGiftUnique

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.231. OwnedGiftRegular

> Describes a regular gift owned by a user or a chat

Describes a regular gift owned by a user or a chat.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| type | String | Always | Type of the gift, always "regular" |
| gift | Gift | Always | Information about the regular gift |
| owned_gift_id | String | Optional | Unique identifier of the gift for the bot; for gifts received on behalf of business accounts only |
| sender_user | User | Optional | Sender of the gift if it is a known user |
| send_date | Integer | Always | Date the gift was sent in Unix time |
| text | String | Optional | Text of the message that was added to the gift |
| entities | Array of MessageEntity | Optional | Special entities that appear in the text |
| is_private | True | Optional | True, if the sender and gift text are shown only to the gift receiver; otherwise, everyone will be able to see them |
| is_saved | True | Optional | True, if the gift is displayed on the account's profile page; for gifts received on behalf of business accounts only |
| can_be_upgraded | True | Optional | True, if the gift can be upgraded to a unique gift; for gifts received on behalf of business accounts only |
| was_refunded | True | Optional | True, if the gift was refunded and isn't available anymore |
| convert_star_count | Integer | Optional | Number of Telegram Stars that can be claimed by the receiver instead of the gift; omitted if the gift cannot be converted to Telegram Stars; for gifts received on behalf of business accounts only |
| prepaid_upgrade_star_count | Integer | Optional | Number of Telegram Stars that were paid for the ability to upgrade the gift |
| is_upgrade_separate | True | Optional | True, if the gift's upgrade was purchased after the gift was sent; for gifts received on behalf of business accounts only |
| unique_gift_number | Integer | Optional | Unique number reserved for this gift when upgraded. See the number field in UniqueGift. |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.232. OwnedGifts

> Contains the list of gifts received and owned by a user or a chat

Contains the list of gifts received and owned by a user or a chat.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| total_count | Integer | Always | The total number of gifts owned by the user or the chat |
| gifts | Array of OwnedGift | Always | The list of gifts |
| next_offset | String | Optional | Offset for the next request. If empty, then there are no more results. |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.233. OwnedGiftUnique

> Describes a unique gift received and owned by a user or a chat

Describes a unique gift received and owned by a user or a chat.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| type | String | Always | Type of the gift, always "unique" |
| gift | UniqueGift | Always | Information about the unique gift |
| owned_gift_id | String | Optional | Unique identifier of the received gift for the bot; for gifts received on behalf of business accounts only |
| sender_user | User | Optional | Sender of the gift if it is a known user |
| send_date | Integer | Always | Date the gift was sent in Unix time |
| is_saved | True | Optional | True, if the gift is displayed on the account's profile page; for gifts received on behalf of business accounts only |
| can_be_transferred | True | Optional | True, if the gift can be transferred to another owner; for gifts received on behalf of business accounts only |
| transfer_star_count | Integer | Optional | Number of Telegram Stars that must be paid to transfer the gift; omitted if the bot cannot transfer the gift |
| next_transfer_date | Integer | Optional | Point in time (Unix timestamp) when the gift can be transferred. If it is in the past, then the gift can be transferred now. |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.234. PaidMedia

> This object describes paid media

This object describes paid media. Currently, it can be one of

* PaidMediaLivePhoto

* PaidMediaPhoto

* PaidMediaPreview

* PaidMediaVideo

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.235. PaidMediaInfo

> Describes the paid media added to a message

Describes the paid media added to a message.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| star_count | Integer | Always | The number of Telegram Stars that must be paid to buy access to the media |
| paid_media | Array of PaidMedia | Always | Information about the paid media |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.236. PaidMediaLivePhoto

> The paid media is a live photo

The paid media is a live photo.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| type | String | Always | Type of the paid media, always "live_photo" |
| live_photo | LivePhoto | Always | The photo |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.237. PaidMediaPhoto

> The paid media is a photo

The paid media is a photo.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| type | String | Always | Type of the paid media, always "photo" |
| photo | Array of PhotoSize | Always | The photo |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.238. PaidMediaPreview

> The paid media isn't available before the payment

The paid media isn't available before the payment.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| type | String | Always | Type of the paid media, always "preview" |
| width | Integer | Optional | Media width as defined by the sender |
| height | Integer | Optional | Media height as defined by the sender |
| duration | Integer | Optional | Duration of the media in seconds as defined by the sender |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.239. PaidMediaPurchased

> This object contains information about a paid media purchase

This object contains information about a paid media purchase.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| from | User | Always | User who purchased the media |
| paid_media_payload | String | Always | Bot-specified paid media payload |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.240. PaidMediaVideo

> The paid media is a video

The paid media is a video.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| type | String | Always | Type of the paid media, always "video" |
| video | Video | Always | The video |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.241. PaidMessagePriceChanged

> Describes a service message about a change in the price of paid messages within a chat

Describes a service message about a change in the price of paid messages within a chat.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| paid_message_star_count | Integer | Always | The new number of Telegram Stars that must be paid by non-administrator users of the supergroup chat for each sent message |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.242. PassportData

> Describes Telegram Passport data shared with the bot by the user

Describes Telegram Passport data shared with the bot by the user.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| data | Array of EncryptedPassportElement | Always | Array with information about documents and other Telegram Passport elements that was shared with the bot |
| credentials | EncryptedCredentials | Always | Encrypted credentials required to decrypt the data |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.243. PassportElementError

> This object represents an error in the Telegram Passport element which was submitted that should be resolved by the user

This object represents an error in the Telegram Passport element which was submitted that should be resolved by the user. It should be one of:

* PassportElementErrorDataField

* PassportElementErrorFrontSide

* PassportElementErrorReverseSide

* PassportElementErrorSelfie

* PassportElementErrorFile

* PassportElementErrorFiles

* PassportElementErrorTranslationFile

* PassportElementErrorTranslationFiles

* PassportElementErrorUnspecified

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.244. PassportElementErrorDataField

> Represents an issue in one of the data fields that was provided by the user

Represents an issue in one of the data fields that was provided by the user. The error is considered resolved when the field's value changes.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| source | String | Always | Error source, must be data |
| type | String | Always | The section of the user's Telegram Passport which has the error, one of "personal_details", "passport", "driver_license", "identity_card", "internal_passport", "address" |
| field_name | String | Always | Name of the data field which has the error |
| data_hash | String | Always | Base64-encoded data hash |
| message | String | Always | Error message |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.245. PassportElementErrorFile

> Represents an issue with a document scan

Represents an issue with a document scan. The error is considered resolved when the file with the document scan changes.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| source | String | Always | Error source, must be file |
| type | String | Always | The section of the user's Telegram Passport which has the issue, one of "utility_bill", "bank_statement", "rental_agreement", "passport_registration", "temporary_registration" |
| file_hash | String | Always | Base64-encoded file hash |
| message | String | Always | Error message |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.246. PassportElementErrorFiles

> Represents an issue with a list of scans

Represents an issue with a list of scans. The error is considered resolved when the list of files containing the scans changes.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| source | String | Always | Error source, must be files |
| type | String | Always | The section of the user's Telegram Passport which has the issue, one of "utility_bill", "bank_statement", "rental_agreement", "passport_registration", "temporary_registration" |
| file_hashes | Array of String | Always | List of base64-encoded file hashes |
| message | String | Always | Error message |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.247. PassportElementErrorFrontSide

> Represents an issue with the front side of a document

Represents an issue with the front side of a document. The error is considered resolved when the file with the front side of the document changes.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| source | String | Always | Error source, must be front_side |
| type | String | Always | The section of the user's Telegram Passport which has the issue, one of "passport", "driver_license", "identity_card", "internal_passport" |
| file_hash | String | Always | Base64-encoded hash of the file with the front side of the document |
| message | String | Always | Error message |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.248. PassportElementErrorReverseSide

> Represents an issue with the reverse side of a document

Represents an issue with the reverse side of a document. The error is considered resolved when the file with reverse side of the document changes.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| source | String | Always | Error source, must be reverse_side |
| type | String | Always | The section of the user's Telegram Passport which has the issue, one of "driver_license", "identity_card" |
| file_hash | String | Always | Base64-encoded hash of the file with the reverse side of the document |
| message | String | Always | Error message |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.249. PassportElementErrorSelfie

> Represents an issue with the selfie with a document

Represents an issue with the selfie with a document. The error is considered resolved when the file with the selfie changes.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| source | String | Always | Error source, must be selfie |
| type | String | Always | The section of the user's Telegram Passport which has the issue, one of "passport", "driver_license", "identity_card", "internal_passport" |
| file_hash | String | Always | Base64-encoded hash of the file with the selfie |
| message | String | Always | Error message |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.250. PassportElementErrorTranslationFile

> Represents an issue with one of the files that constitute the translation of a document

Represents an issue with one of the files that constitute the translation of a document. The error is considered resolved when the file changes.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| source | String | Always | Error source, must be translation_file |
| type | String | Always | Type of element of the user's Telegram Passport which has the issue, one of "passport", "driver_license", "identity_card", "internal_passport", "utility_bill", "bank_statement", "rental_agreement", "passport_registration", "temporary_registration" |
| file_hash | String | Always | Base64-encoded file hash |
| message | String | Always | Error message |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.251. PassportElementErrorTranslationFiles

> Represents an issue with the translated version of a document

Represents an issue with the translated version of a document. The error is considered resolved when a file with the document translation change.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| source | String | Always | Error source, must be translation_files |
| type | String | Always | Type of element of the user's Telegram Passport which has the issue, one of "passport", "driver_license", "identity_card", "internal_passport", "utility_bill", "bank_statement", "rental_agreement", "passport_registration", "temporary_registration" |
| file_hashes | Array of String | Always | List of base64-encoded file hashes |
| message | String | Always | Error message |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.252. PassportElementErrorUnspecified

> Represents an issue in an unspecified place

Represents an issue in an unspecified place. The error is considered resolved when new data is added.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| source | String | Always | Error source, must be unspecified |
| type | String | Always | Type of element of the user's Telegram Passport which has the issue |
| element_hash | String | Always | Base64-encoded element hash |
| message | String | Always | Error message |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.253. PassportFile

> This object represents a file uploaded to Telegram Passport

This object represents a file uploaded to Telegram Passport. Currently all Telegram Passport files are in JPEG format when decrypted and don't exceed 10MB.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| file_id | String | Always | Identifier for this file, which can be used to download or reuse the file |
| file_unique_id | String | Always | Unique identifier for this file, which is supposed to be the same over time and for different bots. Can't be used to download or reuse the file. |
| file_size | Integer | Always | File size in bytes |
| file_date | Integer | Always | Unix time when the file was uploaded |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.254. PhotoSize

> This object represents one size of a photo or a file / sticker thumbnail

This object represents one size of a photo or a file / sticker thumbnail.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| file_id | String | Always | Identifier for this file, which can be used to download or reuse the file |
| file_unique_id | String | Always | Unique identifier for this file, which is supposed to be the same over time and for different bots. Can't be used to download or reuse the file. |
| width | Integer | Always | Photo width |
| height | Integer | Always | Photo height |
| file_size | Integer | Optional | File size in bytes |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.255. Poll

> This object contains information about a poll

This object contains information about a poll.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| id | String | Always | Unique poll identifier |
| question | String | Always | Poll question, 1-300 characters |
| question_entities | Array of MessageEntity | Optional | Special entities that appear in the question. Currently, only custom emoji entities are allowed in poll questions |
| options | Array of PollOption | Always | List of poll options |
| total_voter_count | Integer | Always | Total number of users that voted in the poll |
| is_closed | Boolean | Always | True, if the poll is closed |
| is_anonymous | Boolean | Always | True, if the poll is anonymous |
| type | String | Always | Poll type, currently can be "regular" or "quiz" |
| allows_multiple_answers | Boolean | Always | True, if the poll allows multiple answers |
| allows_revoting | Boolean | Always | True, if the poll allows to change the chosen answer options |
| members_only | Boolean | Always | True if voting is limited to users who have been members of the chat where the poll was originally sent for more than 24 hours |
| country_codes | Array of String | Optional | A list of two-letter ISO 3166-1 alpha-2 country codes indicating the countries from which users can vote in the poll. The country code "FT" is used for users with anonymous numbers. If omitted, then users from any country can participate in the poll. |
| correct_option_ids | Array of Integer | Optional | Array of 0-based identifiers of the correct answer options. Available only for polls in quiz mode which are closed or were sent (not forwarded) by the bot or to the private chat with the bot. |
| explanation | String | Optional | Text that is shown when a user chooses an incorrect answer or taps on the lamp icon in a quiz-style poll, 0-200 characters |
| explanation_entities | Array of MessageEntity | Optional | Special entities like usernames, URLs, bot commands, etc. that appear in the explanation |
| explanation_media | PollMedia | Optional | Media added to the quiz explanation |
| open_period | Integer | Optional | Amount of time in seconds the poll will be active after creation |
| close_date | Integer | Optional | Point in time (Unix timestamp) when the poll will be automatically closed |
| description | String | Optional | Description of the poll; for polls inside the Message object only |
| description_entities | Array of MessageEntity | Optional | Special entities like usernames, URLs, bot commands, etc. that appear in the description |
| media | PollMedia | Optional | Media added to the poll description; for polls inside the Message object only |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.256. PollAnswer

> This object represents an answer of a user in a non-anonymous poll

This object represents an answer of a user in a non-anonymous poll.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| poll_id | String | Always | Unique poll identifier |
| voter_chat | Chat | Optional | The chat that changed the answer to the poll, if the voter is anonymous |
| user | User | Optional | The user that changed the answer to the poll, if the voter isn't anonymous |
| option_ids | Array of Integer | Always | 0-based identifiers of chosen answer options. May be empty if the vote was retracted. |
| option_persistent_ids | Array of String | Always | Persistent identifiers of the chosen answer options. May be empty if the vote was retracted. |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.257. PollMedia

> At most one of the optional fields can be present in any given object

At most **one** of the optional fields can be present in any given object.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| animation | Animation | Optional | Media is an animation, information about the animation |
| audio | Audio | Optional | Media is an audio file, information about the file; currently, can't be received in a poll option |
| document | Document | Optional | Media is a general file, information about the file; currently, can't be received in a poll option |
| link | Link | Optional | The HTTP link attached to the poll option |
| live_photo | LivePhoto | Optional | Media is a live photo, information about the live photo |
| location | Location | Optional | Media is a shared location, information about the location |
| photo | Array of PhotoSize | Optional | Media is a photo, available sizes of the photo |
| sticker | Sticker | Optional | Media is a sticker, information about the sticker; currently, for poll options only |
| venue | Venue | Optional | Media is a venue, information about the venue |
| video | Video | Optional | Media is a video, information about the video |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.258. PollOption

> This object contains information about one answer option in a poll

This object contains information about one answer option in a poll.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| persistent_id | String | Always | Unique identifier of the option, persistent on option addition and deletion |
| text | String | Always | Option text, 1-100 characters |
| text_entities | Array of MessageEntity | Optional | Special entities that appear in the option text. Currently, only custom emoji entities are allowed in poll option texts |
| media | PollMedia | Optional | Media added to the poll option |
| voter_count | Integer | Always | Number of users who voted for this option; may be 0 if unknown |
| added_by_user | User | Optional | User who added the option; omitted if the option wasn't added by a user after poll creation |
| added_by_chat | Chat | Optional | Chat that added the option; omitted if the option wasn't added by a chat after poll creation |
| addition_date | Integer | Optional | Point in time (Unix timestamp) when the option was added; omitted if the option existed in the original poll |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.259. PollOptionAdded

> Describes a service message about an option added to a poll

Describes a service message about an option added to a poll.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| poll_message | MaybeInaccessibleMessage | Optional | Message containing the poll to which the option was added, if known. Note that the Message object in this field will not contain the reply_to_message field even if it itself is a reply. |
| option_persistent_id | String | Always | Unique identifier of the added option |
| option_text | String | Always | Option text |
| option_text_entities | Array of MessageEntity | Optional | Special entities that appear in the option_text |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.260. PollOptionDeleted

> Describes a service message about an option deleted from a poll

Describes a service message about an option deleted from a poll.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| poll_message | MaybeInaccessibleMessage | Optional | Message containing the poll from which the option was deleted, if known. Note that the Message object in this field will not contain the reply_to_message field even if it itself is a reply. |
| option_persistent_id | String | Always | Unique identifier of the deleted option |
| option_text | String | Always | Option text |
| option_text_entities | Array of MessageEntity | Optional | Special entities that appear in the option_text |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.261. PreCheckoutQuery

> This object contains information about an incoming pre-checkout query

This object contains information about an incoming pre-checkout query.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| id | String | Always | Unique query identifier |
| from | User | Always | User who sent the query |
| currency | String | Always | Three-letter ISO 4217 currency code, or "XTR" for payments in Telegram Stars |
| total_amount | Integer | Always | Total price in the smallest units of the currency (integer, not float/double). For example, for a price of US$ 1.45 pass amount = 145. See the exp parameter in currencies.json, it shows the number of digits past the decimal point for each currency (2 for the majority of currencies). |
| invoice_payload | String | Always | Bot-specified invoice payload |
| shipping_option_id | String | Optional | Identifier of the shipping option chosen by the user |
| order_info | OrderInfo | Optional | Order information provided by the user |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.262. PreparedInlineMessage

> Describes an inline message to be sent by a user of a Mini App

Describes an inline message to be sent by a user of a Mini App.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| id | String | Always | Unique identifier of the prepared message |
| expiration_date | Integer | Always | Expiration date of the prepared message, in Unix time. Expired prepared messages can no longer be used. |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.263. PreparedKeyboardButton

> Describes a keyboard button to be used by a user of a Mini App

Describes a keyboard button to be used by a user of a Mini App.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| id | String | Always | Unique identifier of the keyboard button |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.264. ProximityAlertTriggered

> This object represents the content of a service message, sent whenever a user in the chat triggers a proximity alert set by another user

This object represents the content of a service message, sent whenever a user in the chat triggers a proximity alert set by another user.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| traveler | User | Always | User that triggered the alert |
| watcher | User | Always | User that set the alert |
| distance | Integer | Always | The distance between the users |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.265. ReactionCount

> Represents a reaction added to a message along with the number of times it was added

Represents a reaction added to a message along with the number of times it was added.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| type | ReactionType | Always | Type of the reaction |
| total_count | Integer | Always | Number of times the reaction was added |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.266. ReactionType

> This object describes the type of a reaction

This object describes the type of a reaction. Currently, it can be one of

* ReactionTypeEmoji

* ReactionTypeCustomEmoji

* ReactionTypePaid

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.267. ReactionTypeCustomEmoji

> The reaction is based on a custom emoji

The reaction is based on a custom emoji.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| type | String | Always | Type of the reaction, always "custom_emoji" |
| custom_emoji_id | String | Always | Custom emoji identifier |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.268. ReactionTypeEmoji

> The reaction is based on an emoji.

The reaction is based on an emoji.

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| type | String | Always | Type of the reaction, always "emoji" |
| emoji | String | Always | Reaction emoji. Currently, it can be one of "❤", "👍", "👎", "🔥", "🥰", "👏", "😁", "🤔", "🤯", "😱", "🤬", "😢", "🎉", "🤩", "🤮", "💩", "🙏", "👌", "🕊", "🤡", "🥱", "🥴", "😍", "🐳", "❤‍🔥", "🌚", "🌭", "💯", "🤣", "⚡", "🍌", "🏆", "💔", "🤨", "😐", "🍓", "🍾", "💋", "🖕", "😈", "😴", "😭", "🤓", "👻", "👨‍💻", "👀", "🎃", "🙈", "😇", "😨", "🤝", "✍", "🤗", "🫡", "🎅", "🎄", "☃", "💅", "🤪", "🗿", "🆒", "💘", "🙉", "🦄", "😘", "💊", "🙊", "😎", "👾", "🤷‍♂", "🤷", "🤷‍♀", "😡" |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.269. ReactionTypePaid

> The reaction is paid

The reaction is paid.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| type | String | Always | Type of the reaction, always "paid" |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.270. RefundedPayment

> This object contains basic information about a refunded payment

This object contains basic information about a refunded payment.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| currency | String | Always | Three-letter ISO 4217 currency code, or "XTR" for payments in Telegram Stars. Currently, always "XTR". |
| total_amount | Integer | Always | Total refunded price in the smallest units of the currency (integer, not float/double). For example, for a price of US$ 1.45, total_amount = 145. See the exp parameter in currencies.json, it shows the number of digits past the decimal point for each currency (2 for the majority of currencies). |
| invoice_payload | String | Always | Bot-specified invoice payload |
| telegram_payment_charge_id | String | Always | Telegram payment identifier |
| provider_payment_charge_id | String | Optional | Provider payment identifier |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.271. ReplyKeyboardMarkup

> This object represents a custom keyboard with reply options (see Introduction to bots for details and examples)

This object represents a custom keyboard with reply options (see Introduction to bots for details and examples). Not supported in channels and for messages sent on behalf of a business account.

*Example:* A user requests to change the bot's language, bot replies to the request with a keyboard to select the new language. Other users in the group don't see the keyboard.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| keyboard | Array of Array of KeyboardButton | Always | Array of button rows, each represented by an Array of KeyboardButton objects |
| is_persistent | Boolean | Optional | Requests clients to always show the keyboard when the regular keyboard is hidden. Defaults to False, in which case the custom keyboard can be hidden and opened with a keyboard icon. |
| resize_keyboard | Boolean | Optional | Requests clients to resize the keyboard vertically for optimal fit (e.g., make the keyboard smaller if there are just two rows of buttons). Defaults to False, in which case the custom keyboard is always of the same height as the app's standard keyboard. |
| one_time_keyboard | Boolean | Optional | Requests clients to hide the keyboard as soon as it's been used. The keyboard will still be available, but clients will automatically display the usual letter-keyboard in the chat - the user can press a special button in the input field to see the custom keyboard again. Defaults to False. |
| input_field_placeholder | String | Optional | The placeholder to be shown in the input field when the keyboard is active; 1-64 characters |
| selective | Boolean | Optional | Use this parameter if you want to show the keyboard to specific users only. Targets: 1) users that are @mentioned in the text of the Message object; 2) if the bot's message is a reply to a message in the same chat and forum topic, sender of the original message. |

#### Example

```php
{
  "keyboard": [
    [{"text": "📊 My Balance"}, {"text": "💰 Deposit"}],
    [{"text": "🎯 Invite Friends"}, {"text": "ℹ️ Help"}]
  ],
  "resize_keyboard": true,
  "is_persistent": true,
  "input_field_placeholder": "Choose an option…"
}
```

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.272. ReplyKeyboardRemove

> Upon receiving a message with this object, Telegram clients will remove the current custom keyboard and display the default letter-keyboard

Upon receiving a message with this object, Telegram clients will remove the current custom keyboard and display the default letter-keyboard. By default, custom keyboards are displayed until a new keyboard is sent by a bot. An exception is made for one-time keyboards that are hidden immediately after the user presses a button (see ReplyKeyboardMarkup). Not supported in channels and for messages sent on behalf of a business account.

*Example:* A user votes in a poll, bot returns confirmation message in reply to the vote and removes the keyboard for that user, while still showing the keyboard with poll options to users who haven't voted yet.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| remove_keyboard | True | Always | Requests clients to remove the custom keyboard (user will not be able to summon this keyboard; if you want to hide the keyboard from sight but keep it accessible, use one_time_keyboard in ReplyKeyboardMarkup) |
| selective | Boolean | Optional | Use this parameter if you want to remove the keyboard for specific users only. Targets: 1) users that are @mentioned in the text of the Message object; 2) if the bot's message is a reply to a message in the same chat and forum topic, sender of the original message. |

#### Example

```php
{"remove_keyboard": true, "selective": false}
```

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.273. ReplyParameters

> Describes reply parameters for the message that is being sent

Describes reply parameters for the message that is being sent.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| message_id | Integer | Optional | Identifier of the message that will be replied to in the current chat, or in the chat chat_id if it is specified. Required if ephemeral_message_id isn't specified. |
| chat_id | Integer or String | Optional | If the message to be replied to is from a different chat, unique identifier for the chat or username of the bot, supergroup or channel in the format @username. Not supported for messages sent on behalf of a business account, messages from channel direct messages chats and ephemeral messages. |
| ephemeral_message_id | Integer | Optional | Identifier of the incoming ephemeral message that will be replied to in the current chat. A reply to an ephemeral message must itself be an ephemeral message. An ephemeral message may only be replied to within 15 seconds of being sent. Required if message_id isn't specified. |
| allow_sending_without_reply | Boolean | Optional | Pass True if the message should be sent even if the specified message to be replied to is not found. Always False for replies in another chat or forum topic, and sent ephemeral messages. Always True for messages sent on behalf of a business account. |
| quote | String | Optional | Quoted part of the message to be replied to; 0-1024 characters after entities parsing. The quote must be an exact substring of the message to be replied to, including bold, italic, underline, strikethrough, spoiler, custom_emoji, and date_time entities. The message will fail to send if the quote isn't found in the original message. Ignored for ephemeral messages. |
| quote_parse_mode | String | Optional | Mode for parsing entities in the quote. See formatting options for more details. |
| quote_entities | Array of MessageEntity | Optional | A JSON-serialized list of special entities that appear in the quote. It can be specified instead of quote_parse_mode. |
| quote_position | Integer | Optional | Position of the quote in the original message in UTF-16 code units |
| checklist_task_id | Integer | Optional | Identifier of the specific checklist task to be replied to |
| poll_option_id | String | Optional | Persistent identifier of the specific poll option to be replied to |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.274. ResponseParameters

> Describes why a request was unsuccessful

Describes why a request was unsuccessful.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| migrate_to_chat_id | Integer | Optional | The group has been migrated to a supergroup with the specified identifier. This number may have more than 32 significant bits and some programming languages may have difficulty/silent defects in interpreting it. But it has at most 52 significant bits, so a signed 64-bit integer or double-precision float type are safe for storing this identifier. |
| retry_after | Integer | Optional | In case of exceeding flood control, the number of seconds left to wait before the request can be repeated |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.275. RevenueWithdrawalState

> This object describes the state of a revenue withdrawal operation

This object describes the state of a revenue withdrawal operation. Currently, it can be one of

* RevenueWithdrawalStatePending

* RevenueWithdrawalStateSucceeded

* RevenueWithdrawalStateFailed

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.276. RevenueWithdrawalStateFailed

> The withdrawal failed and the transaction was refunded

The withdrawal failed and the transaction was refunded.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| type | String | Always | Type of the state, always "failed" |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.277. RevenueWithdrawalStatePending

> The withdrawal is in progress

The withdrawal is in progress.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| type | String | Always | Type of the state, always "pending" |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.278. RevenueWithdrawalStateSucceeded

> The withdrawal succeeded

The withdrawal succeeded.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| type | String | Always | Type of the state, always "succeeded" |
| date | Integer | Always | Date the withdrawal was completed in Unix time |
| url | String | Always | An HTTPS URL that can be used to see transaction details |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.279. richblock

> This object represents a block in a rich formatted message

This object represents a block in a rich formatted message. Currently, it can be any of the following types:

* RichBlockParagraph

* RichBlockSectionHeading

* RichBlockPreformatted

* RichBlockFooter

* RichBlockDivider

* RichBlockMathematicalExpression

* RichBlockAnchor

* RichBlockList

* RichBlockBlockQuotation

* RichBlockExpandableBlockQuotation

* RichBlockPullQuotation

* RichBlockCollage

* RichBlockSlideshow

* RichBlockTable

* RichBlockDetails

* RichBlockMap

* RichBlockButtons

* RichBlockAnimation

* RichBlockAudio

* RichBlockDocument

* RichBlockPhoto

* RichBlockVideo

* RichBlockVoiceNote

* RichBlockThinking

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.280. richblockanchor

> A block with an anchor, corresponding to the HTML tag <a> with the attribute name

A block with an anchor, corresponding to the HTML tag `<a>` with the attribute `name`.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| type | String | Always | Type of the block, always "anchor" |
| name | String | Always | The name of the anchor |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.281. richblockanimation

> A block with an animation, corresponding to the HTML tag <video>

A block with an animation, corresponding to the HTML tag `<video>`.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| type | String | Always | Type of the block, always "animation" |
| animation | Animation | Always | The animation |
| has_spoiler | True | Optional | True, if the media preview is covered by a spoiler animation |
| caption | RichBlockCaption | Optional | Caption of the block |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.282. richblockaudio

> A block with a music file, corresponding to the HTML tag <audio>

A block with a music file, corresponding to the HTML tag `<audio>`.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| type | String | Always | Type of the block, always "audio" |
| audio | Audio | Always | The audio |
| caption | RichBlockCaption | Optional | Caption of the block |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.283. richblockblockquotation

> A block quotation, corresponding to the HTML tag <blockquote>

A block quotation, corresponding to the HTML tag `<blockquote>`.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| type | String | Always | Type of the block, always "blockquote" |
| blocks | Array of RichBlock | Always | Content of the block |
| credit | RichText | Optional | Credit of the block |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.284. richblockbuttons

> A block containing a list of buttons that are shown in one row, corresponding to the custom HTML tag <tg-button-row>

A block containing a list of buttons that are shown in one row, corresponding to the custom HTML tag `<tg-button-row>`.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| type | String | Always | Type of the block, always "buttons" |
| buttons | Array of RichMessageButton | Always | The buttons |
| align | String | Optional | Horizontal alignment of the buttons. Currently, must be one of "left", "center", or "right". |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.285. richblockcaption

> Caption of a rich formatted block

Caption of a rich formatted block.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| text | RichText | Always | Block caption |
| credit | RichText | Optional | Block credit which corresponds to the HTML tag <cite> |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.286. richblockcollage

> A collage, corresponding to the custom HTML tag <tg-collage>

A collage, corresponding to the custom HTML tag `<tg-collage>`.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| type | String | Always | Type of the block, always "collage" |
| blocks | Array of RichBlock | Always | Elements of the collage |
| caption | RichBlockCaption | Optional | Caption of the block |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.287. richblockdetails

> An expandable block for details disclosure, corresponding to the HTML tag <details>

An expandable block for details disclosure, corresponding to the HTML tag `<details>`.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| type | String | Always | Type of the block, always "details" |
| summary | RichText | Always | Always shown summary of the block |
| blocks | Array of RichBlock | Always | Content of the block |
| is_open | True | Optional | True, if the content of the block is visible by default |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.288. richblockdivider

> A divider, corresponding to the HTML tag <hr/>

A divider, corresponding to the HTML tag `<hr/>`.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| type | String | Always | Type of the block, always "divider" |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.289. richblockdocument

> A block with a general file, corresponding to the custom HTML tag <tg-document>

A block with a general file, corresponding to the custom HTML tag `<tg-document>`.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| type | String | Always | Type of the block, always "document" |
| document | Document | Always | The document |
| caption | RichBlockCaption | Optional | Caption of the block |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.290. richblockexpandableblockquotation

> A block quotation, corresponding to the HTML tag <blockquote> with custom attribute "expandable"

A block quotation, corresponding to the HTML tag `<blockquote>` with custom attribute `"expandable"`.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| type | String | Always | Type of the block, always "expandable_blockquote" |
| text | RichText | Always | Content of the block |
| credit | RichText | Optional | Credit of the block |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.291. richblockfooter

> A footer, corresponding to the HTML tag <footer>

A footer, corresponding to the HTML tag `<footer>`.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| type | String | Always | Type of the block, always "footer" |
| text | RichText | Always | Text of the block |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.292. richblocklist

> A list of blocks, corresponding to the HTML tag <ul> or <ol> with multiple nested tags <li>

A list of blocks, corresponding to the HTML tag `<ul>` or `<ol>` with multiple nested tags `<li>`.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| type | String | Always | Type of the block, always "list" |
| items | Array of RichBlockListItem | Always | Items of the list |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.293. richblocklistitem

> An item of a list.

An item of a list.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| label | String | Always | Label of the item |
| blocks | Array of RichBlock | Always | The content of the item |
| has_checkbox | True | Optional | True, if the item has a checkbox |
| is_checked | True | Optional | True, if the item has a checked checkbox |
| value | Integer | Optional | For ordered lists, the numeric value of the item label |
| type | String | Optional | For ordered lists, the type of the item label; must be one of "a" for lowercase letters, "A" for uppercase letters, "i" for lowercase Roman numerals, "I" for uppercase Roman numerals, or "1" for decimal numbers |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.294. richblockmap

> A block with a map, corresponding to the custom HTML tag <tg-map>

A block with a map, corresponding to the custom HTML tag `<tg-map>`.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| type | String | Always | Type of the block, always "map" |
| location | Location | Always | Location of the center of the map |
| zoom | Integer | Always | Map zoom level |
| width | Integer | Always | Expected width of the map |
| height | Integer | Always | Expected height of the map |
| caption | RichBlockCaption | Optional | Caption of the block |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.295. richblockmathematicalexpression

> A block with a mathematical expression in LaTeX format, corresponding to the custom HTML tag <tg-math-block>

A block with a mathematical expression in LaTeX format, corresponding to the custom HTML tag `<tg-math-block>`.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| type | String | Always | Type of the block, always "mathematical_expression" |
| expression | String | Always | The mathematical expression in LaTeX format |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.296. richblockparagraph

> A text paragraph, corresponding to the HTML tag <p>

A text paragraph, corresponding to the HTML tag `<p>`.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| type | String | Always | Type of the block, always "paragraph" |
| text | RichText | Always | Text of the block |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.297. richblockphoto

> A block with a photo, corresponding to the HTML tag <img>

A block with a photo, corresponding to the HTML tag `<img>`.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| type | String | Always | Type of the block, always "photo" |
| photo | Array of PhotoSize | Always | Available sizes of the photo |
| has_spoiler | True | Optional | True, if the media preview is covered by a spoiler animation |
| caption | RichBlockCaption | Optional | Caption of the block |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.298. richblockpreformatted

> A preformatted text block, corresponding to the nested HTML tags <pre> and <code>

A preformatted text block, corresponding to the nested HTML tags `<pre>` and `<code>`.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| type | String | Always | Type of the block, always "pre" |
| text | RichText | Always | Text of the block |
| language | String | Optional | The programming language of the text |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.299. richblockpullquotation

> A quotation with centered text, loosely corresponding to the HTML tag <aside>

A quotation with centered text, loosely corresponding to the HTML tag `<aside>`.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| type | String | Always | Type of the block, always "pullquote" |
| text | RichText | Always | Text of the block |
| credit | RichText | Optional | Credit of the block |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.300. richblocksectionheading

> A section heading, corresponding to the HTML tags <h1>, <h2>, <h3>, <h4>, <h5>, or <h6>

A section heading, corresponding to the HTML tags `<h1>`, `<h2>`, `<h3>`, `<h4>`, `<h5>`, or `<h6>`.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| type | String | Always | Type of the block, always "heading" |
| text | RichText | Always | Text of the block |
| size | Integer | Always | Relative size of the text font; 1-6, 1 is the largest, 6 is the smallest |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.301. richblockslideshow

> A slideshow, corresponding to the custom HTML tag <tg-slideshow>

A slideshow, corresponding to the custom HTML tag `<tg-slideshow>`.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| type | String | Always | Type of the block, always "slideshow" |
| blocks | Array of RichBlock | Always | Elements of the slideshow |
| caption | RichBlockCaption | Optional | Caption of the block |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.302. richblocktable

> A table, corresponding to the HTML tag <table>

A table, corresponding to the HTML tag `<table>`.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| type | String | Always | Type of the block, always "table" |
| cells | Array of Array of RichBlockTableCell | Always | Cells of the table |
| is_bordered | True | Optional | True, if the table has borders |
| is_striped | True | Optional | True, if the table is striped |
| is_compact | True | Optional | True, if table cells have smaller indents |
| caption | RichText | Optional | Caption of the table |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.303. richblocktablecell

> Cell in a table.

Cell in a table.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| text | RichText | Optional | Text in the cell. If omitted, then the cell is invisible. |
| is_header | True | Optional | True, if the cell is a header cell |
| colspan | Integer | Optional | The number of columns the cell spans if it is bigger than 1 |
| rowspan | Integer | Optional | The number of rows the cell spans if it is bigger than 1 |
| align | String | Always | Horizontal cell content alignment. Currently, must be one of "left", "center", or "right". |
| valign | String | Always | Vertical cell content alignment. Currently, must be one of "top", "middle", or "bottom". |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.304. richblockthinking

> A block with a "Thinking..." placeholder, corresponding to the custom HTML tag <tg-thinking>

A block with a "Thinking..." placeholder, corresponding to the custom HTML tag `<tg-thinking>`. The block may be used only in sendRichMessageDraft, therefore it can't be received in messages. See https://t.me/addemoji/AIActions for examples of custom emoji that are recommended for usage in the block.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| type | String | Always | Type of the block, always "thinking" |
| text | RichText | Always | Text of the block. See https://t.me/addemoji/AIActions for examples of custom emoji that are recommended for usage in the block. |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.305. richblockvideo

> A block with a video, corresponding to the HTML tag <video>

A block with a video, corresponding to the HTML tag `<video>`.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| type | String | Always | Type of the block, always "video" |
| video | Video | Always | The video |
| has_spoiler | True | Optional | True, if the media preview is covered by a spoiler animation |
| caption | RichBlockCaption | Optional | Caption of the block |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.306. richblockvoicenote

> A block with a voice note, corresponding to the HTML tag <audio>

A block with a voice note, corresponding to the HTML tag `<audio>`.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| type | String | Always | Type of the block, always "voice_note" |
| voice_note | Voice | Always | The voice note |
| caption | RichBlockCaption | Optional | Caption of the block |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.307. richmessage

> Rich formatted message

Rich formatted message.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| blocks | Array of RichBlock | Always | Content of the message |
| is_rtl | Boolean | Optional | True, if the rich message must be shown right-to-left |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.308. richmessagebutton

> This object represents a button in a RichMessage

This object represents a button in a RichMessage. Exactly one of the fields other than *text* and *style* must be used to specify the type of the button.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| text | RichText | Always | Text of the button. May contain only plain text, RichTextCustomEmoji and RichTextDateTime entities. |
| style | String | Optional | Style of the button. Must be one of "danger", "success", "primary", or "link" (the button is shown as a regular link without borders). Apps may use theme-specific colors for the button background and text based on the style. The style "link" is allowed only for callback buttons. |
| url | String | Optional | HTTP or tg:// URL to be opened when the button is pressed. Links tg://user?id= can be used to mention a user by their identifier without using a username, if this is allowed by their privacy settings. |
| callback_data | String | Optional | Data to be sent in a callback query to the bot when the button is pressed, 1-64 bytes |
| web_app | WebAppInfo | Optional | Description of the Web App that will be launched when the user presses the button. The Web App will be able to send an arbitrary message on behalf of the user using the method answerWebAppQuery. Available only in private chats between a user and the bot. Not supported for messages sent on behalf of a business account. |
| login_url | LoginUrl | Optional | An HTTPS URL used to automatically authorize the user. Can be used as a replacement for the Telegram Login Widget. Not supported for ephemeral messages. |
| switch_inline_query | String | Optional | If set, pressing the button will prompt the user to select one of their chats, open that chat and insert the bot's username and the specified inline query in the input field. May be empty, in which case just the bot's username will be inserted. Not supported for messages sent in channel direct messages chats and on behalf of a business account. |
| switch_inline_query_current_chat | String | Optional | If set, pressing the button will insert the bot's username and the specified inline query in the current chat's input field. May be empty, in which case only the bot's username will be inserted. Not supported in channels and for messages sent in channel direct messages chats and on behalf of a business account. |
| switch_inline_query_chosen_chat | SwitchInlineQueryChosenChat | Optional | If set, pressing the button will prompt the user to select one of their chats of the specified type, open that chat and insert the bot's username and the specified inline query in the input field. Not supported for messages sent in channel direct messages chats and on behalf of a business account. |
| copy_text | CopyTextButton | Optional | A button that copies the specified text to the clipboard |
| disabled | DisabledButton | Optional | If set, then the button is disabled and does nothing |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.309. richtext

> This object represents a rich formatted text

This object represents a rich formatted text. Currently, it can be either a String for plain text, an Array of RichText, or any of the following types:

* RichTextBold

* RichTextItalic

* RichTextUnderline

* RichTextStrikethrough

* RichTextSpoiler

* RichTextDateTime

* RichTextTextMention

* RichTextSubscript

* RichTextSuperscript

* RichTextMarked

* RichTextCode

* RichTextCustomEmoji

* RichTextMathematicalExpression

* RichTextUrl

* RichTextEmailAddress

* RichTextPhoneNumber

* RichTextBankCardNumber

* RichTextMention

* RichTextHashtag

* RichTextCashtag

* RichTextBotCommand

* RichTextButton

* RichTextAnchor

* RichTextAnchorLink

* RichTextReference

* RichTextReferenceLink

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.310. richtextanchor

> An anchor.

An anchor.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| type | String | Always | Type of the rich text, always "anchor" |
| name | String | Always | The name of the anchor |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.311. richtextanchorlink

> A link to an anchor.

A link to an anchor.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| type | String | Always | Type of the rich text, always "anchor_link" |
| text | RichText | Always | The link text |
| anchor_name | String | Always | The name of the anchor. If the name is empty, then the link brings back to the top of the message. |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.312. richtextbankcardnumber

> A text with a bank card number

A text with a bank card number.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| type | String | Always | Type of the rich text, always "bank_card_number" |
| text | RichText | Always | The text |
| bank_card_number | String | Always | The bank card number |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.313. richtextbold

> A bold text.

A bold text.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| type | String | Always | Type of the rich text, always "bold" |
| text | RichText | Always | The text |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.314. richtextbotcommand

> A bot command.

A bot command.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| type | String | Always | Type of the rich text, always "bot_command" |
| text | RichText | Always | The text |
| bot_command | String | Always | The bot command |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.315. richtextbutton

> A button.

A button.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| type | String | Always | Type of the rich text, always "button" |
| button | RichMessageButton | Always | The button |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.316. richtextcashtag

> A cashtag.

A cashtag.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| type | String | Always | Type of the rich text, always "cashtag" |
| text | RichText | Always | The text |
| cashtag | String | Always | The cashtag |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.317. richtextcode

> A monowidth text.

A monowidth text.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| type | String | Always | Type of the rich text, always "code" |
| text | RichText | Always | The text |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.318. richtextcustomemoji

> A custom emoji.

A custom emoji.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| type | String | Always | Type of the rich text, always "custom_emoji" |
| custom_emoji_id | String | Always | Unique identifier of the custom emoji. Use getCustomEmojiStickers to get full information about the sticker. |
| alternative_text | String | Always | Alternative emoji for the custom emoji |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.319. richtextdatetime

> Formatted date and time

Formatted date and time.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| type | String | Always | Type of the rich text, always "date_time" |
| text | RichText | Always | The text |
| unix_time | Integer | Always | The Unix time associated with the entity |
| date_time_format | String | Always | The string that defines the formatting of the date and time. See date-time entity formatting for more details. |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.320. richtextemailaddress

> A text with an email address

A text with an email address.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| type | String | Always | Type of the rich text, always "email_address" |
| text | RichText | Always | The text |
| email_address | String | Always | The email address |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.321. richtexthashtag

> A hashtag.

A hashtag.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| type | String | Always | Type of the rich text, always "hashtag" |
| text | RichText | Always | The text |
| hashtag | String | Always | The hashtag |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.322. richtextitalic

> An italicized text.

An italicized text.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| type | String | Always | Type of the rich text, always "italic" |
| text | RichText | Always | The text |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.323. richtextmarked

> A marked text.

A marked text.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| type | String | Always | Type of the rich text, always "marked" |
| text | RichText | Always | The text |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.324. richtextmathematicalexpression

> A mathematical expression

A mathematical expression.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| type | String | Always | Type of the rich text, always "mathematical_expression" |
| expression | String | Always | The expression in LaTeX format |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.325. richtextmention

> A mention by a username

A mention by a username.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| type | String | Always | Type of the rich text, always "mention" |
| text | RichText | Always | The text |
| username | String | Always | The username |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.326. richtextphonenumber

> A text with a phone number

A text with a phone number.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| type | String | Always | Type of the rich text, always "phone_number" |
| text | RichText | Always | The text |
| phone_number | String | Always | The phone number |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.327. richtextreference

> A reference.

A reference.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| type | String | Always | Type of the rich text, always "reference" |
| text | RichText | Always | Text of the reference |
| name | String | Always | The name of the reference |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.328. richtextreferencelink

> A link to a reference

A link to a reference.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| type | String | Always | Type of the rich text, always "reference_link" |
| text | RichText | Always | The link text |
| reference_name | String | Always | The name of the reference |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.329. richtextspoiler

> A text covered by a spoiler

A text covered by a spoiler.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| type | String | Always | Type of the rich text, always "spoiler" |
| text | RichText | Always | The text |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.330. richtextstrikethrough

> A strikethrough text

A strikethrough text.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| type | String | Always | Type of the rich text, always "strikethrough" |
| text | RichText | Always | The text |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.331. richtextsubscript

> A subscript text.

A subscript text.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| type | String | Always | Type of the rich text, always "subscript" |
| text | RichText | Always | The text |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.332. richtextsuperscript

> A superscript text.

A superscript text.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| type | String | Always | Type of the rich text, always "superscript" |
| text | RichText | Always | The text |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.333. richtexttextmention

> A mention of a Telegram user by their identifier

A mention of a Telegram user by their identifier.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| type | String | Always | Type of the rich text, always "text_mention" |
| text | RichText | Always | The text |
| user | User | Always | The mentioned user |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.334. richtextunderline

> An underlined text.

An underlined text.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| type | String | Always | Type of the rich text, always "underline" |
| text | RichText | Always | The text |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.335. richtexturl

> A text with a link.

A text with a link.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| type | String | Always | Type of the rich text, always "url" |
| text | RichText | Always | The text |
| url | String | Always | URL of the link |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.336. SentGuestMessage

> Describes an inline message sent by a guest bot

Describes an inline message sent by a guest bot.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| inline_message_id | String | Always | Identifier of the sent inline message |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.337. SentWebAppMessage

> Describes an inline message sent by a Web App on behalf of a user

Describes an inline message sent by a Web App on behalf of a user.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| inline_message_id | String | Optional | Identifier of the sent inline message. Available only if there is an inline keyboard attached to the message. |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.338. SharedUser

> This object contains information about a user that was shared with the bot using a KeyboardButtonRequestUsers button

This object contains information about a user that was shared with the bot using a KeyboardButtonRequestUsers button.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| user_id | Integer | Always | Identifier of the shared user. This number may have more than 32 significant bits and some programming languages may have difficulty/silent defects in interpreting it. But it has at most 52 significant bits, so 64-bit integers or double-precision float types are safe for storing these identifiers. The bot may not have access to the user and could be unable to use this identifier, unless the user is already known to the bot by some other means. |
| first_name | String | Optional | First name of the user, if the name was requested by the bot |
| last_name | String | Optional | Last name of the user, if the name was requested by the bot |
| username | String | Optional | Username of the user, if the username was requested by the bot |
| photo | Array of PhotoSize | Optional | Available sizes of the chat photo, if the photo was requested by the bot |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.339. ShippingAddress

> This object represents a shipping address

This object represents a shipping address.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| country_code | String | Always | Two-letter ISO 3166-1 alpha-2 country code |
| state | String | Always | State, if applicable |
| city | String | Always | City |
| street_line1 | String | Always | First line for the address |
| street_line2 | String | Always | Second line for the address |
| post_code | String | Always | Address post code |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.340. ShippingOption

> This object represents one shipping option

This object represents one shipping option.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| id | String | Always | Shipping option identifier |
| title | String | Always | Option title |
| prices | Array of LabeledPrice | Always | List of price portions |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.341. ShippingQuery

> This object contains information about an incoming shipping query

This object contains information about an incoming shipping query.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| id | String | Always | Unique query identifier |
| from | User | Always | User who sent the query |
| invoice_payload | String | Always | Bot-specified invoice payload |
| shipping_address | ShippingAddress | Always | User specified shipping address |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.342. StarAmount

> Describes an amount of Telegram Stars

Describes an amount of Telegram Stars.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| amount | Integer | Always | Integer amount of Telegram Stars, rounded to 0; can be negative |
| nanostar_amount | Integer | Optional | The number of 1/1000000000 shares of Telegram Stars; from -999999999 to 999999999; can be negative if and only if amount is non-positive |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.343. StarTransaction

> Describes a Telegram Star transaction

Describes a Telegram Star transaction. Note that if the buyer initiates a chargeback with the payment provider from whom they acquired Stars (e.g., Apple, Google) following this transaction, the refunded Stars will be deducted from the bot's balance. This is outside of Telegram's control.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| id | String | Always | Unique identifier of the transaction. Coincides with the identifier of the original transaction for refund transactions. Coincides with SuccessfulPayment.telegram_payment_charge_id for successful incoming payments from users. |
| amount | Integer | Always | Integer amount of Telegram Stars transferred by the transaction |
| nanostar_amount | Integer | Optional | The number of 1/1000000000 shares of Telegram Stars transferred by the transaction; from 0 to 999999999 |
| date | Integer | Always | Date the transaction was created in Unix time |
| source | TransactionPartner | Optional | Source of an incoming transaction (e.g., a user purchasing goods or services, Fragment refunding a failed withdrawal). Only for incoming transactions. |
| receiver | TransactionPartner | Optional | Receiver of an outgoing transaction (e.g., a user for a purchase refund, Fragment for a withdrawal). Only for outgoing transactions. |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.344. StarTransactions

> Contains a list of Telegram Star transactions

Contains a list of Telegram Star transactions.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| transactions | Array of StarTransaction | Always | The list of transactions |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.345. Sticker

> This object represents a sticker

This object represents a sticker.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| file_id | String | Always | Identifier for this file, which can be used to download or reuse the file |
| file_unique_id | String | Always | Unique identifier for this file, which is supposed to be the same over time and for different bots. Can't be used to download or reuse the file. |
| type | String | Always | Type of the sticker, currently one of "regular", "mask", "custom_emoji". The type of the sticker is independent from its format, which is determined by the fields is_animated and is_video. |
| width | Integer | Always | Sticker width |
| height | Integer | Always | Sticker height |
| is_animated | Boolean | Always | True, if the sticker is animated |
| is_video | Boolean | Always | True, if the sticker is a video sticker |
| thumbnail | PhotoSize | Optional | Sticker thumbnail in the .WEBP or .JPG format |
| emoji | String | Optional | Emoji associated with the sticker |
| set_name | String | Optional | Name of the sticker set to which the sticker belongs |
| premium_animation | File | Optional | For premium regular stickers, premium animation for the sticker |
| mask_position | MaskPosition | Optional | For mask stickers, the position where the mask should be placed |
| custom_emoji_id | String | Optional | For custom emoji stickers, unique identifier of the custom emoji |
| needs_repainting | True | Optional | True, if the sticker must be repainted to a text color in messages, the color of the Telegram Premium badge in emoji status, white color on chat photos, or another appropriate color in other places |
| file_size | Integer | Optional | File size in bytes |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.346. StickerSet

> This object represents a sticker set

This object represents a sticker set.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| name | String | Always | Sticker set name |
| title | String | Always | Sticker set title |
| sticker_type | String | Always | Type of stickers in the set, currently one of "regular", "mask", "custom_emoji" |
| stickers | Array of Sticker | Always | List of all set stickers |
| thumbnail | PhotoSize | Optional | Sticker set thumbnail in the .WEBP, .TGS, or .WEBM format |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.347. Story

> This object represents a story

This object represents a story.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| chat | Chat | Always | Chat that posted the story |
| id | Integer | Always | Unique identifier for the story in the chat |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.348. StoryArea

> Describes a clickable area on a story media

Describes a clickable area on a story media.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| position | StoryAreaPosition | Always | Position of the area |
| type | StoryAreaType | Always | Type of the area |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.349. StoryAreaPosition

> Describes the position of a clickable area within a story

Describes the position of a clickable area within a story.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| x_percentage | Float | Always | The abscissa of the area's center, as a percentage of the media width |
| y_percentage | Float | Always | The ordinate of the area's center, as a percentage of the media height |
| width_percentage | Float | Always | The width of the area's rectangle, as a percentage of the media width |
| height_percentage | Float | Always | The height of the area's rectangle, as a percentage of the media height |
| rotation_angle | Float | Always | The clockwise rotation angle of the rectangle, in degrees; 0-360 |
| corner_radius_percentage | Float | Always | The radius of the rectangle corner rounding, as a percentage of the media width |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.350. StoryAreaType

> Describes the type of a clickable area on a story

Describes the type of a clickable area on a story. Currently, it can be one of

* StoryAreaTypeLocation

* StoryAreaTypeSuggestedReaction

* StoryAreaTypeLink

* StoryAreaTypeWeather

* StoryAreaTypeUniqueGift

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.351. StoryAreaTypeLink

> Describes a story area pointing to an HTTP or tg:// link

Describes a story area pointing to an HTTP or tg:// link. Currently, a story can have up to 3 link areas.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| type | String | Always | Type of the area, always "link" |
| url | String | Always | HTTP or tg:// URL to be opened when the area is clicked |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.352. StoryAreaTypeLocation

> Describes a story area pointing to a location

Describes a story area pointing to a location. Currently, a story can have up to 10 location areas.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| type | String | Always | Type of the area, always "location" |
| latitude | Float | Always | Location latitude in degrees |
| longitude | Float | Always | Location longitude in degrees |
| address | LocationAddress | Optional | Address of the location |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.353. StoryAreaTypeSuggestedReaction

> Describes a story area pointing to a suggested reaction

Describes a story area pointing to a suggested reaction. Currently, a story can have up to 5 suggested reaction areas.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| type | String | Always | Type of the area, always "suggested_reaction" |
| reaction_type | ReactionType | Always | Type of the reaction |
| is_dark | Boolean | Optional | Pass True if the reaction area has a dark background |
| is_flipped | Boolean | Optional | Pass True if reaction area corner is flipped |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.354. StoryAreaTypeUniqueGift

> Describes a story area pointing to a unique gift

Describes a story area pointing to a unique gift. Currently, a story can have at most 1 unique gift area.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| type | String | Always | Type of the area, always "unique_gift" |
| name | String | Always | Unique name of the gift |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.355. StoryAreaTypeWeather

> Describes a story area containing weather information

Describes a story area containing weather information. Currently, a story can have up to 3 weather areas.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| type | String | Always | Type of the area, always "weather" |
| temperature | Float | Always | Temperature, in degree Celsius |
| emoji | String | Always | Emoji representing the weather |
| background_color | Integer | Always | A color of the area background in the ARGB format |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.356. SuccessfulPayment

> This object contains basic information about a successful payment

This object contains basic information about a successful payment. Note that if the buyer initiates a chargeback with the relevant payment provider following this transaction, the funds may be debited from your balance. This is outside of Telegram's control.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| currency | String | Always | Three-letter ISO 4217 currency code, or "XTR" for payments in Telegram Stars |
| total_amount | Integer | Always | Total price in the smallest units of the currency (integer, not float/double). For example, for a price of US$ 1.45 pass amount = 145. See the exp parameter in currencies.json, it shows the number of digits past the decimal point for each currency (2 for the majority of currencies). |
| invoice_payload | String | Always | Bot-specified invoice payload |
| subscription_expiration_date | Integer | Optional | Expiration date of the subscription, in Unix time; for recurring payments only |
| is_recurring | True | Optional | True, if the payment is a recurring payment for a subscription |
| is_first_recurring | True | Optional | True, if the payment is the first payment for a subscription |
| shipping_option_id | String | Optional | Identifier of the shipping option chosen by the user |
| order_info | OrderInfo | Optional | Order information provided by the user |
| telegram_payment_charge_id | String | Always | Telegram payment identifier |
| provider_payment_charge_id | String | Always | Provider payment identifier |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.357. SuggestedPostApprovalFailed

> Describes a service message about the failed approval of a suggested post

Describes a service message about the failed approval of a suggested post. Currently, only caused by insufficient user funds at the time of approval.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| suggested_post_message | Message | Optional | Message containing the suggested post whose approval has failed. Note that the Message object in this field will not contain the reply_to_message field even if it itself is a reply. |
| price | SuggestedPostPrice | Always | Expected price of the post |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.358. SuggestedPostApproved

> Describes a service message about the approval of a suggested post

Describes a service message about the approval of a suggested post.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| suggested_post_message | Message | Optional | Message containing the suggested post. Note that the Message object in this field will not contain the reply_to_message field even if it itself is a reply. |
| price | SuggestedPostPrice | Optional | Amount paid for the post |
| send_date | Integer | Always | Date when the post will be published |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.359. SuggestedPostDeclined

> Describes a service message about the rejection of a suggested post

Describes a service message about the rejection of a suggested post.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| suggested_post_message | Message | Optional | Message containing the suggested post. Note that the Message object in this field will not contain the reply_to_message field even if it itself is a reply. |
| comment | String | Optional | Comment with which the post was declined |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.360. SuggestedPostInfo

> Contains information about a suggested post

Contains information about a suggested post.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| state | String | Always | State of the suggested post. Currently, it can be one of "pending", "approved", "declined". |
| price | SuggestedPostPrice | Optional | Proposed price of the post. If the field is omitted, then the post is unpaid. |
| send_date | Integer | Optional | Proposed send date of the post. If the field is omitted, then the post can be published at any time within 30 days at the sole discretion of the user or administrator who approves it. |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.361. SuggestedPostPaid

> Describes a service message about a successful payment for a suggested post

Describes a service message about a successful payment for a suggested post.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| suggested_post_message | Message | Optional | Message containing the suggested post. Note that the Message object in this field will not contain the reply_to_message field even if it itself is a reply. |
| currency | String | Always | Currency in which the payment was made. Currently, one of "XTR" for Telegram Stars or "TON" for TON grams. |
| amount | Integer | Optional | The amount of the currency that was received by the channel in nanograms; for payments in TON grams only |
| star_amount | StarAmount | Optional | The amount of Telegram Stars that was received by the channel; for payments in Telegram Stars only |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.362. SuggestedPostParameters

> Contains parameters of a post that is being suggested by the bot

Contains parameters of a post that is being suggested by the bot.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| price | SuggestedPostPrice | Optional | Proposed price for the post. If the field is omitted, then the post is unpaid. |
| send_date | Integer | Optional | Proposed send date of the post. If specified, then the date must be between 300 second and 2678400 seconds (30 days) in the future. If the field is omitted, then the post can be published at any time within 30 days at the sole discretion of the user who approves it. |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.363. SuggestedPostPrice

> Describes the price of a suggested post

Describes the price of a suggested post.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| currency | String | Always | Currency in which the post will be paid. Currently, must be one of "XTR" for Telegram Stars or "TON" for TON grams. |
| amount | Integer | Always | The amount of the currency that will be paid for the post in the smallest units of the currency, i.e. Telegram Stars or nanograms. Currently, price in Telegram Stars must be between 5 and 100000, and price in nanograms must be between 10000000 and 10000000000000. |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.364. SuggestedPostRefunded

> Describes a service message about a payment refund for a suggested post

Describes a service message about a payment refund for a suggested post.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| suggested_post_message | Message | Optional | Message containing the suggested post. Note that the Message object in this field will not contain the reply_to_message field even if it itself is a reply. |
| reason | String | Always | Reason for the refund. Currently, one of "post_deleted" if the post was deleted within 24 hours of being posted or removed from scheduled messages without being posted, or "payment_refunded" if the payer refunded their payment. |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.365. SwitchInlineQueryChosenChat

> This object represents an inline button that switches the current user to inline mode in a chosen chat, with an optional default inline query

This object represents an inline button that switches the current user to inline mode in a chosen chat, with an optional default inline query.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| query | String | Optional | The default inline query to be inserted in the input field. If left empty, only the bot's username will be inserted. |
| allow_user_chats | Boolean | Optional | True, if private chats with users can be chosen |
| allow_bot_chats | Boolean | Optional | True, if private chats with bots can be chosen |
| allow_group_chats | Boolean | Optional | True, if group and supergroup chats can be chosen |
| allow_channel_chats | Boolean | Optional | True, if channel chats can be chosen |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.366. TextQuote

> This object contains information about the quoted part of a message that is replied to by the given message

This object contains information about the quoted part of a message that is replied to by the given message.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| text | String | Always | Text of the quoted part of a message that is replied to by the given message |
| entities | Array of MessageEntity | Optional | Special entities that appear in the quote. Currently, only bold, italic, underline, strikethrough, spoiler, custom_emoji, and date_time entities are kept in quotes. |
| position | Integer | Always | Approximate quote position in the original message in UTF-16 code units as specified by the sender |
| is_manual | True | Optional | True, if the quote was chosen manually by the message sender. Otherwise, the quote was added automatically by the server. |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.367. TransactionPartner

> This object describes the source of a transaction, or its recipient for outgoing transactions

This object describes the source of a transaction, or its recipient for outgoing transactions. Currently, it can be one of

* TransactionPartnerUser

* TransactionPartnerChat

* TransactionPartnerAffiliateProgram

* TransactionPartnerFragment

* TransactionPartnerTelegramAds

* TransactionPartnerTelegramApi

* TransactionPartnerOther

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.368. TransactionPartnerAffiliateProgram

> Describes the affiliate program that issued the affiliate commission received via this transaction

Describes the affiliate program that issued the affiliate commission received via this transaction.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| type | String | Always | Type of the transaction partner, always "affiliate_program" |
| sponsor_user | User | Optional | Information about the bot that sponsored the affiliate program |
| commission_per_mille | Integer | Always | The number of Telegram Stars received by the bot for each 1000 Telegram Stars received by the affiliate program sponsor from referred users |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.369. TransactionPartnerChat

> Describes a transaction with a chat

Describes a transaction with a chat.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| type | String | Always | Type of the transaction partner, always "chat" |
| chat | Chat | Always | Information about the chat |
| gift | Gift | Optional | The gift sent to the chat by the bot |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.370. TransactionPartnerFragment

> Describes a withdrawal transaction with Fragment

Describes a withdrawal transaction with Fragment.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| type | String | Always | Type of the transaction partner, always "fragment" |
| withdrawal_state | RevenueWithdrawalState | Optional | State of the transaction if the transaction is outgoing |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.371. TransactionPartnerOther

> Describes a transaction with an unknown source or recipient

Describes a transaction with an unknown source or recipient.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| type | String | Always | Type of the transaction partner, always "other" |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.372. TransactionPartnerTelegramAds

> Describes a withdrawal transaction to the Telegram Ads platform

Describes a withdrawal transaction to the Telegram Ads platform.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| type | String | Always | Type of the transaction partner, always "telegram_ads" |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.373. TransactionPartnerTelegramApi

> Describes a transaction with payment for paid broadcasting

Describes a transaction with payment for paid broadcasting.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| type | String | Always | Type of the transaction partner, always "telegram_api" |
| request_count | Integer | Always | The number of successful requests that exceeded regular limits and were therefore billed |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.374. TransactionPartnerUser

> Describes a transaction with a user

Describes a transaction with a user.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| type | String | Always | Type of the transaction partner, always "user" |
| transaction_type | String | Always | Type of the transaction, currently one of "invoice_payment" for payments via invoices, "paid_media_payment" for payments for paid media, "gift_purchase" for gifts sent by the bot, "premium_purchase" for Telegram Premium subscriptions gifted by the bot, "business_account_transfer" for direct transfers from managed business accounts |
| user | User | Always | Information about the user |
| affiliate | AffiliateInfo | Optional | Information about the affiliate that received a commission via this transaction. Can be available only for "invoice_payment" and "paid_media_payment" transactions. |
| invoice_payload | String | Optional | Bot-specified invoice payload. Can be available only for "invoice_payment" transactions. |
| subscription_period | Integer | Optional | The duration of the paid subscription. Can be available only for "invoice_payment" transactions. |
| paid_media | Array of PaidMedia | Optional | Information about the paid media bought by the user; for "paid_media_payment" transactions only |
| paid_media_payload | String | Optional | Bot-specified paid media payload. Can be available only for "paid_media_payment" transactions. |
| gift | Gift | Optional | The gift sent to the user by the bot; for "gift_purchase" transactions only |
| premium_subscription_duration | Integer | Optional | Number of months the gifted Telegram Premium subscription will be active for; for "premium_purchase" transactions only |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.375. UniqueGift

> This object describes a unique gift that was upgraded from a regular gift

This object describes a unique gift that was upgraded from a regular gift.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| gift_id | String | Always | Identifier of the regular gift from which the gift was upgraded |
| base_name | String | Always | Human-readable name of the regular gift from which this unique gift was upgraded |
| name | String | Always | Unique name of the gift. This name can be used in https://t.me/nft/... links and story areas. |
| number | Integer | Always | Unique number of the upgraded gift among gifts upgraded from the same regular gift |
| model | UniqueGiftModel | Always | Model of the gift |
| symbol | UniqueGiftSymbol | Always | Symbol of the gift |
| backdrop | UniqueGiftBackdrop | Always | Backdrop of the gift |
| is_premium | True | Optional | True, if the original regular gift was exclusively purchaseable by Telegram Premium subscribers |
| is_burned | True | Optional | True, if the gift was used to craft another gift and isn't available anymore |
| is_from_blockchain | True | Optional | True, if the gift is assigned from the TON blockchain and can't be resold or transferred in Telegram |
| colors | UniqueGiftColors | Optional | The color scheme that can be used by the gift's owner for the chat's name, replies to messages and link previews; for business account gifts and gifts that are currently on sale only |
| publisher_chat | Chat | Optional | Information about the chat that published the gift |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.376. UniqueGiftBackdrop

> This object describes the backdrop of a unique gift

This object describes the backdrop of a unique gift.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| name | String | Always | Name of the backdrop |
| colors | UniqueGiftBackdropColors | Always | Colors of the backdrop |
| rarity_per_mille | Integer | Always | The number of unique gifts that receive this backdrop for every 1000 gifts upgraded |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.377. UniqueGiftBackdropColors

> This object describes the colors of the backdrop of a unique gift

This object describes the colors of the backdrop of a unique gift.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| center_color | Integer | Always | The color in the center of the backdrop in RGB format |
| edge_color | Integer | Always | The color on the edges of the backdrop in RGB format |
| symbol_color | Integer | Always | The color to be applied to the symbol in RGB format |
| text_color | Integer | Always | The color for the text on the backdrop in RGB format |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.378. UniqueGiftColors

> This object contains information about the color scheme for a user's name, message replies and link previews based on a unique gift

This object contains information about the color scheme for a user's name, message replies and link previews based on a unique gift.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| model_custom_emoji_id | String | Always | Custom emoji identifier of the unique gift's model |
| symbol_custom_emoji_id | String | Always | Custom emoji identifier of the unique gift's symbol |
| light_theme_main_color | Integer | Always | Main color used in light themes; RGB format |
| light_theme_other_colors | Array of Integer | Always | List of 1-3 additional colors used in light themes; RGB format |
| dark_theme_main_color | Integer | Always | Main color used in dark themes; RGB format |
| dark_theme_other_colors | Array of Integer | Always | List of 1-3 additional colors used in dark themes; RGB format |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.379. UniqueGiftInfo

> Describes a service message about a unique gift that was sent or received

Describes a service message about a unique gift that was sent or received.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| gift | UniqueGift | Always | Information about the gift |
| origin | String | Always | Origin of the gift. Currently, either "upgrade" for gifts upgraded from regular gifts, "transfer" for gifts transferred from other users or channels, "resale" for gifts bought from other users, "gifted_upgrade" for upgrades purchased after the gift was sent, or "offer" for gifts bought or sold through gift purchase offers. |
| text | String | Optional | Text of the message that was added to the gift |
| entities | Array of MessageEntity | Optional | Special entities that appear in the text |
| is_private | True | Optional | True, if the sender and gift text are shown only to the gift receiver; otherwise, everyone will be able to see them |
| last_resale_currency | String | Optional | For gifts bought from other users, the currency in which the payment for the gift was done. Currently, one of "XTR" for Telegram Stars or "TON" for TON grams. |
| last_resale_amount | Integer | Optional | For gifts bought from other users, the price paid for the gift in either Telegram Stars or nanograms |
| owned_gift_id | String | Optional | Unique identifier of the received gift for the bot; only present for gifts received on behalf of business accounts |
| transfer_star_count | Integer | Optional | Number of Telegram Stars that must be paid to transfer the gift; omitted if the bot cannot transfer the gift |
| next_transfer_date | Integer | Optional | Point in time (Unix timestamp) when the gift can be transferred. If it is in the past, then the gift can be transferred now. |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.380. UniqueGiftModel

> This object describes the model of a unique gift

This object describes the model of a unique gift.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| name | String | Always | Name of the model |
| sticker | Sticker | Always | The sticker that represents the unique gift |
| rarity_per_mille | Integer | Always | The number of unique gifts that receive this model for every 1000 gift upgrades. Always 0 for crafted gifts. |
| rarity | String | Optional | Rarity of the model if it is a crafted model. Currently, can be "uncommon", "rare", "epic", or "legendary". |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.381. UniqueGiftSymbol

> This object describes the symbol shown on the pattern of a unique gift

This object describes the symbol shown on the pattern of a unique gift.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| name | String | Always | Name of the symbol |
| sticker | Sticker | Always | The sticker that represents the unique gift |
| rarity_per_mille | Integer | Always | The number of unique gifts that receive this model for every 1000 gifts upgraded |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.382. Update

> This object represents an incoming update

This object represents an incoming update.

At most **one** of the optional fields can be present in any given update.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| update_id | Integer | Always | The update's unique identifier. Update identifiers start from a certain positive number and increase sequentially. This identifier becomes especially handy if you're using webhooks, since it allows you to ignore repeated updates or to restore the correct update sequence, should they get out of order. If there are no new updates for at least a week, then identifier of the next update will be chosen randomly instead of sequentially. |
| message | Message | Optional | New incoming message of any kind - text, photo, sticker, etc. |
| edited_message | Message | Optional | New version of a message that is known to the bot and was edited. This update may at times be triggered by changes to message fields that are either unavailable or not actively used by your bot. |
| channel_post | Message | Optional | New incoming channel post of any kind - text, photo, sticker, etc. |
| edited_channel_post | Message | Optional | New version of a channel post that is known to the bot and was edited. This update may at times be triggered by changes to message fields that are either unavailable or not actively used by your bot. |
| business_connection | BusinessConnection | Optional | The bot was connected to or disconnected from a business account, or a user edited an existing connection with the bot |
| business_message | Message | Optional | New message from a connected business account |
| edited_business_message | Message | Optional | New version of a message from a connected business account |
| deleted_business_messages | BusinessMessagesDeleted | Optional | Messages were deleted from a connected business account |
| guest_message | Message | Optional | New guest message. The bot can use the field Message.guest_query_id and the method answerGuestQuery to send a message in response. |
| message_reaction | MessageReactionUpdated | Optional | A reaction to a message was changed by a user. The bot must be an administrator in the chat and must explicitly specify "message_reaction" in the list of allowed_updates to receive these updates. The update isn't received for reactions set by bots. |
| message_reaction_count | MessageReactionCountUpdated | Optional | Reactions to a message with anonymous reactions were changed. The bot must be an administrator in the chat and must explicitly specify "message_reaction_count" in the list of allowed_updates to receive these updates. The updates are grouped and can be sent with delay up to a few minutes. |
| inline_query | InlineQuery | Optional | New incoming inline query |
| chosen_inline_result | ChosenInlineResult | Optional | The result of an inline query that was chosen by a user and sent to their chat partner. Please see our documentation on the feedback collecting for details on how to enable these updates for your bot. |
| callback_query | CallbackQuery | Optional | New incoming callback query |
| shipping_query | ShippingQuery | Optional | New incoming shipping query. Only for invoices with flexible price. |
| pre_checkout_query | PreCheckoutQuery | Optional | New incoming pre-checkout query. Contains full information about checkout. |
| purchased_paid_media | PaidMediaPurchased | Optional | A user purchased paid media with a non-empty payload sent by the bot in a non-channel chat |
| poll | Poll | Optional | New poll state. Bots receive only updates about manually stopped polls and polls, which are sent by the bot. |
| poll_answer | PollAnswer | Optional | A user changed their answer in a non-anonymous poll. Bots receive new votes only in polls that were sent by the bot itself. |
| my_chat_member | ChatMemberUpdated | Optional | The bot's chat member status was updated in a chat. For private chats, this update is received only when the bot is blocked or unblocked by the user. |
| chat_member | ChatMemberUpdated | Optional | A chat member's status was updated in a chat. The bot must be an administrator in the chat and must explicitly specify "chat_member" in the list of allowed_updates to receive these updates. |
| chat_join_request | ChatJoinRequest | Optional | A request to join the chat has been sent. The bot must have the can_invite_users administrator right in the chat to receive these updates. |
| chat_boost | ChatBoostUpdated | Optional | A chat boost was added or changed. The bot must be an administrator in the chat to receive these updates. |
| removed_chat_boost | ChatBoostRemoved | Optional | A boost was removed from a chat. The bot must be an administrator in the chat to receive these updates. |
| managed_bot | ManagedBotUpdated | Optional | A new bot was created to be managed by the bot, or token or owner of a managed bot was changed |
| subscription | BotSubscriptionUpdated | Optional | User payment subscription has changed |
| stopped_message_generation | MessageGenerationStopped | Optional | A user asked the bot to stop the generation of a message |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.383. User

> This object represents a Telegram user or bot

This object represents a Telegram user or bot.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| id | Integer | Always | Unique identifier for this user or bot. This number may have more than 32 significant bits and some programming languages may have difficulty/silent defects in interpreting it. But it has at most 52 significant bits, so a 64-bit integer or double-precision float type are safe for storing this identifier. |
| is_bot | Boolean | Always | True, if this user is a bot |
| first_name | String | Always | User's or bot's first name |
| last_name | String | Optional | User's or bot's last name |
| username | String | Optional | User's or bot's username |
| language_code | String | Optional | IETF language tag of the user's language |
| is_premium | True | Optional | True, if this user is a Telegram Premium user |
| added_to_attachment_menu | True | Optional | True, if this user added the bot to the attachment menu |
| can_join_groups | Boolean | Optional | True, if the bot can be invited to groups. Returned only in getMe. |
| can_read_all_group_messages | Boolean | Optional | True, if privacy mode is disabled for the bot. Returned only in getMe. |
| supports_guest_queries | Boolean | Optional | True, if the bot supports guest queries from chats it is not a member of. Returned only in getMe. |
| supports_inline_queries | Boolean | Optional | True, if the bot supports inline queries. Returned only in getMe. |
| can_connect_to_business | Boolean | Optional | True, if the bot can be connected to a user account to manage it. Returned only in getMe. |
| has_main_web_app | Boolean | Optional | True, if the bot has a main Web App. Returned only in getMe. |
| has_topics_enabled | Boolean | Optional | True, if the bot has forum topic mode enabled in private chats. Returned only in getMe. |
| allows_users_to_create_topics | Boolean | Optional | True, if the bot allows users to create and delete topics in private chats. Returned only in getMe. |
| can_manage_bots | Boolean | Optional | True, if other bots can be created to be controlled by the bot. Returned only in getMe. |
| supports_join_request_queries | Boolean | Optional | True, if the bot supports join request queries and can be assigned to process them. Returned only in getMe. |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.384. UserChatBoosts

> This object represents a list of boosts added to a chat by a user

This object represents a list of boosts added to a chat by a user.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| boosts | Array of ChatBoost | Always | The list of boosts added to the chat by the user |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.385. UserProfileAudios

> This object represents the audios displayed on a user's profile

This object represents the audios displayed on a user's profile.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| total_count | Integer | Always | Total number of profile audios for the target user |
| audios | Array of Audio | Always | Requested profile audios |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.386. UserProfilePhotos

> This object represent a user's profile pictures

This object represent a user's profile pictures.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| total_count | Integer | Always | Total number of profile pictures the target user has |
| photos | Array of Array of PhotoSize | Always | Requested profile pictures (in up to 4 sizes each) |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.387. UserRating

> This object describes the rating of a user based on their Telegram Star spendings

This object describes the rating of a user based on their Telegram Star spendings.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| level | Integer | Always | Current level of the user, indicating their reliability when purchasing digital goods and services. A higher level suggests a more trustworthy customer; a negative level is likely reason for concern. |
| rating | Integer | Always | Numerical value of the user's rating; the higher the rating, the better |
| current_level_rating | Integer | Always | The rating value required to get the current level |
| next_level_rating | Integer | Optional | The rating value required to get to the next level; omitted if the maximum level was reached |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.388. UsersShared

> This object contains information about the users whose identifiers were shared with the bot using a KeyboardButtonRequestUsers button

This object contains information about the users whose identifiers were shared with the bot using a KeyboardButtonRequestUsers button.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| request_id | Integer | Always | Identifier of the request |
| users | Array of SharedUser | Always | Information about users shared with the bot |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.389. Venue

> This object represents a venue

This object represents a venue.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| location | Location | Always | Venue location. Can't be a live location. |
| title | String | Always | Name of the venue |
| address | String | Always | Address of the venue |
| foursquare_id | String | Optional | Foursquare identifier of the venue |
| foursquare_type | String | Optional | Foursquare type of the venue. (For example, "arts_entertainment/default", "arts_entertainment/aquarium" or "food/icecream".) |
| google_place_id | String | Optional | Google Places identifier of the venue |
| google_place_type | String | Optional | Google Places type of the venue. (See supported types.) |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.390. Video

> This object represents a video file

This object represents a video file.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| file_id | String | Always | Identifier for this file, which can be used to download or reuse the file |
| file_unique_id | String | Always | Unique identifier for this file, which is supposed to be the same over time and for different bots. Can't be used to download or reuse the file. |
| width | Integer | Always | Video width as defined by the sender |
| height | Integer | Always | Video height as defined by the sender |
| duration | Integer | Always | Duration of the video in seconds as defined by the sender |
| thumbnail | PhotoSize | Optional | Video thumbnail |
| cover | Array of PhotoSize | Optional | Available sizes of the cover of the video in the message |
| start_timestamp | Integer | Optional | Timestamp in seconds from which the video will play in the message |
| qualities | Array of VideoQuality | Optional | List of available qualities of the video |
| file_name | String | Optional | Original filename as defined by the sender |
| mime_type | String | Optional | MIME type of the file as defined by the sender |
| file_size | Integer | Optional | File size in bytes. It can be bigger than 2^31 and some programming languages may have difficulty/silent defects in interpreting it. But it has at most 52 significant bits, so a signed 64-bit integer or double-precision float type are safe for storing this value. |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.391. VideoChatEnded

> This object represents a service message about a video chat ended in the chat

This object represents a service message about a video chat ended in the chat.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| duration | Integer | Always | Video chat duration in seconds |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.392. VideoChatParticipantsInvited

> This object represents a service message about new members invited to a video chat

This object represents a service message about new members invited to a video chat.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| users | Array of User | Always | New members that were invited to the video chat |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.393. VideoChatScheduled

> This object represents a service message about a video chat scheduled in the chat

This object represents a service message about a video chat scheduled in the chat.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| start_date | Integer | Always | Point in time (Unix timestamp) when the video chat is supposed to be started by a chat administrator |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.394. VideoChatStarted

> This object represents a service message about a video chat started in the chat

This object represents a service message about a video chat started in the chat. Currently holds no information.

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.395. VideoNote

> This object represents a video message

This object represents a video message.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| file_id | String | Always | Identifier for this file, which can be used to download or reuse the file |
| file_unique_id | String | Always | Unique identifier for this file, which is supposed to be the same over time and for different bots. Can't be used to download or reuse the file. |
| length | Integer | Always | Video width and height (diameter of the video message) as defined by the sender |
| duration | Integer | Always | Duration of the video in seconds as defined by the sender |
| thumbnail | PhotoSize | Optional | Video thumbnail |
| file_size | Integer | Optional | File size in bytes |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.396. VideoQuality

> This object represents a video file of a specific quality

This object represents a video file of a specific quality.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| file_id | String | Always | Identifier for this file, which can be used to download or reuse the file |
| file_unique_id | String | Always | Unique identifier for this file, which is supposed to be the same over time and for different bots. Can't be used to download or reuse the file. |
| width | Integer | Always | Video width |
| height | Integer | Always | Video height |
| codec | String | Always | Codec that was used to encode the video, for example, "h264", "h265", or "av01" |
| file_size | Integer | Optional | File size in bytes. It can be bigger than 2^31 and some programming languages may have difficulty/silent defects in interpreting it. But it has at most 52 significant bits, so a signed 64-bit integer or double-precision float type are safe for storing this value. |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.397. Voice

> This object represents a voice note

This object represents a voice note.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| file_id | String | Always | Identifier for this file, which can be used to download or reuse the file |
| file_unique_id | String | Always | Unique identifier for this file, which is supposed to be the same over time and for different bots. Can't be used to download or reuse the file. |
| duration | Integer | Always | Duration of the audio in seconds as defined by the sender |
| mime_type | String | Optional | MIME type of the file as defined by the sender |
| file_size | Integer | Optional | File size in bytes. It can be bigger than 2^31 and some programming languages may have difficulty/silent defects in interpreting it. But it has at most 52 significant bits, so a signed 64-bit integer or double-precision float type are safe for storing this value. |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.398. WebAppData

> Describes data sent from a Web App to the bot

Describes data sent from a Web App to the bot.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| data | String | Always | The data. Be aware that a bad client can send arbitrary data in this field. |
| button_text | String | Always | Text of the web_app keyboard button from which the Web App was opened. Be aware that a bad client can send arbitrary data in this field. |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.399. WebAppInfo

> Describes a Web App.

Describes a Web App.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| url | String | Always | An HTTPS URL of a Web App to be opened with additional data as specified in Initializing Web Apps |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.400. WebhookInfo

> Describes the current status of a webhook

Describes the current status of a webhook.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| url | String | Always | Webhook URL, may be empty if webhook is not set up |
| has_custom_certificate | Boolean | Always | True, if a custom certificate was provided for webhook certificate checks |
| pending_update_count | Integer | Always | Number of updates awaiting delivery |
| ip_address | String | Optional | Currently used webhook IP address |
| last_error_date | Integer | Optional | Unix time for the most recent error that happened when trying to deliver an update via webhook |
| last_error_message | String | Optional | Error message in human-readable format for the most recent error that happened when trying to deliver an update via webhook |
| last_synchronization_error_date | Integer | Optional | Unix time of the most recent error that happened when trying to synchronize available updates with Telegram datacenters |
| max_connections | Integer | Optional | The maximum allowed number of simultaneous HTTPS connections to the webhook for update delivery |
| allowed_updates | Array of String | Optional | A list of update types the bot is subscribed to. Defaults to all update types except chat_member, message_reaction, and message_reaction_count. |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

### 13.401. WriteAccessAllowed

> This object represents a service message about a user allowing a bot to write messages after adding it to the attachment menu, launching a W

This object represents a service message about a user allowing a bot to write messages after adding it to the attachment menu, launching a Web App from a link, or accepting an explicit request from a Web App sent by the method requestWriteAccess.

#### Fields

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| from_request | Boolean | Optional | True, if the access was granted after the user accepted an explicit request from a Web App sent by the method requestWriteAccess |
| web_app_name | String | Optional | Name of the Web App, if the access was granted when the Web App was launched from a link |
| from_attachment_menu | Boolean | Optional | True, if the access was granted when the bot was added to the attachment or side menu |

> [!TIP]
> **Botlify Cloud Runtime**
> Credentials are auto-injected in .env — always load them with getenv(): BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME. Main database: database.db (SQLite, WAL mode). Runtime errors: error.log. Quick test: send to $ADMIN_CHAT_ID. Full details: Runtime Reference.

---

## 14. 📚 Platform Developer Guides & Studio Manuals (34 In-Depth Guides)

This section compiles all specialized Botlify Cloud platform architectural guides, Webhook simulators, Studio Web IDE walkthroughs, AI prompt blueprints, and troubleshooting manuals.

### 14.1. [Getting Started] Welcome to Botlify Cloud

> High-performance, zero-config cloud hosting and developer studio for Telegram bots.

#### What is Botlify Cloud?

   

**Botlify Cloud** is a modern, enterprise-grade cloud hosting and orchestration platform built specifically for Telegram bots. It eliminates the traditional headaches of server provisioning, SSL certificates, webhook registration, and database management, allowing you to deploy production-ready bots in under 60 seconds.

   
> [!TIP]
> **Instant Live Webhooks**
> Botlify automatically configures HTTPS SSL webhooks with Telegram's servers the instant you provide a token. No manual webhook URLs or SSL certificates needed!

   

#### Core Platform Highlights

   
    
- **Zero-Config PHP 8.2+ Runtime:** High-speed execution with OPcache and native cURL optimization.

    
- **Isolated Per-Bot Sandboxes:** Each bot runs in its own directory with dedicated files, dependencies, and independent storage quotas (15 MB+ per bot).

    
- **Embedded SQLite 3 Studio:** Integrated database engine running WAL mode for lightning-fast concurrent reads and writes with zero database configuration.

    
- **AI Model Context Protocol (MCP) Server:** Connect your favorite AI IDEs (Cursor, Windsurf, Claude Desktop, Antigravity) to manage bots, edit code, query databases, and deploy autonomously.

    
- **Integrated Webhook Simulator:** Test bot commands, simulated `/start` payloads, and inspect error logs without triggering live Telegram messages.

    
- **Automated Cron Scheduler:** Schedule background workers (e.g. daily claim resets, cleanup tasks, notifications) down to 1-minute intervals.

   

   

#### Platform Architecture at a Glance

   
    
| Component | Specification | Description |
| --- | --- | --- |
| Runtime | PHP 8.2+ / 8.3 CLI & FPM | Isolated sandbox process with strict error reporting and fast execution. |
| Storage | NVMe SSD Isolated Folders | 15 MB default dedicated quota per bot; upgradable via referrals and admin. |
| Database | SQLite 3 with WAL Mode | Zero-maintenance relational database included with every bot (database.db). |
| AI Integration | MCP (Model Context Protocol) | Standard JSON-RPC 2.0 / SSE endpoint at /mcp.php for AI agents. |
| Security | Protected .env & Sandboxing | Hardware-isolated credentials with automatic access control and secret masking. |

---

### 14.2. [Getting Started] 60-Second Quickstart

> Deploy your first Telegram bot from scratch to live production in 60 seconds.

#### Prerequisites

   

Before launching your first bot, ensure you have:

   
    
- An active account on [Botlify Cloud](https://botlify.cloud/login.php).

    
- A Telegram account to chat with **@BotFather**.

   

   

#### Step 1: Obtain Bot Token from @BotFather

   

Open Telegram and search for `@BotFather`. Send the command `/newbot` and follow the interactive prompts:

   
   
```php
/newbot
Alright, a new bot. How are we going to call it? Please choose a name for your bot.
My First Cloud Bot
Good. Now let's choose a username for your bot. It must end in 'bot'. Like this, for example: TetrisBot or tetris_bot.
my_first_cloud_bot
Done! Congratulations on your new bot. You will find it at t.me/my_first_cloud_bot.
Use this token to access the HTTP API:
7123456789:AAHq_EXAMPLE_TOKEN_ABC123XYZ
```

   

#### Step 2: Deploy on Botlify Cloud

   
    
- Navigate to your [Botlify Dashboard](https://botlify.cloud/dashboard.php).

    
- Click the **Deploy Bot** (or **+ New Bot**) button in the top navigation bar.

    
- Paste your Telegram Bot Token into the input field.

    
- Select your preferred bot scaffold (e.g. *Styled Keyboards & Dashboard* or *Refer-to-Earn Bot*).

    
- Click **Deploy Bot Now**.

   

   
> [!TIP]
> **Instant Webhook Activation**
> Botlify immediately registers the Telegram Webhook and sets up the native menu button. Click the generated t.me/... link and press /start to interact with your live bot!

---

### 14.3. [Getting Started] 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.

#### 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.

---

### 14.4. [Getting Started] Botlify Native Helper Functions (tg_send, tg_request & Cheatsheet)

> Master Botlify's built-in high-speed Telegram shorthand functions — send messages, edit text, build keyboards, check channel membership, and download media in 1 line of code.

#### Botlify Cloud Native Telegram Runtime Helpers

Botlify Cloud includes a built-in suite of **high-performance Telegram shorthand functions (`tg_*`)** pre-loaded into the runtime memory. By using these native helpers, you can build production-ready Telegram bots with **90% less boilerplate code** — no third-party SDKs, no Composer dependencies, and no vendor directories required.

> [!TIP]
> **Zero-Configuration & Automatic Token Binding**
> All tg_* functions automatically detect your bot's token from the Botlify environment (.env) and memory sandbox. You do not need to manually pass the bot token to every function call, and child bot tokens are strictly isolated so they never leak into platform credentials.

#### 1. Quick Reference & Cheatsheet

The table below summarizes all native shorthand functions available in the Botlify Cloud runtime:

| Function | Description | Example |
| --- | --- | --- |
| tg_send($chatId, $text, $extra) | Sends an HTML formatted message with web preview disabled by default. | tg_send($chatId, "Hello!"); |
| tg_request($method, $params) | Universal Telegram API caller. Runs any official Telegram method. | tg_request('sendChatAction', ['chat_id'=>$id, 'action'=>'typing']); |
| tg_edit($chatId, $msgId, $text, $extra) | Edits an existing text message seamlessly. | tg_edit($chatId, $msgId, "Updated text"); |
| tg_edit_caption($chatId, $msgId, $caption) | Edits the caption of an existing photo, video, or document. | tg_edit_caption($chatId, $msgId, "New caption"); |
| tg_edit_markup($chatId, $msgId, $markup) | Modifies inline keyboard buttons without re-rendering or touching the text. | tg_edit_markup($chatId, $msgId, $keyboard); |
| tg_delete($chatId, $msgId) | Deletes a message from a chat or channel in 1 line. | tg_delete($chatId, $msgId); |
| tg_answer_cb($cbId, $text, $alert) | Dismisses button loading spinners; displays toast notification or modal alert. | tg_answer_cb($cbId, "Done!"); |
| tg_copy($to, $from, $msgId, $extra) | Copies any message (text, media, sticker) without a "Forwarded" header. | tg_copy($channelId, $chatId, $msgId); |
| tg_is_member($channel, $userId) | Checks if a user is subscribed to a channel/group. Returns true or false. | if (tg_is_member('@mychannel', $userId)) { ... } |
| tg_send_media($type, $chatId, $file, $caption) | Sends photos, documents, videos, audio, or animations from URL or local path. | tg_send_media('photo', $chatId, 'https://.../img.jpg'); |
| tg_btn($text, $callbackData) | Creates an inline callback button array. | $btn = tg_btn("Confirm", "action_confirm"); |
| tg_url_btn($text, $url) | Creates an inline URL button array. | $btn = tg_url_btn("Website", "https://..."); |
| tg_webapp_btn($text, $url) | Creates a Telegram Mini App button. | $btn = tg_webapp_btn("Open App", "https://..."); |
| tg_inline($rows) | Wraps an array of button rows into ['inline_keyboard' => $rows]. | $kb = tg_inline([[$b1, $b2]]); |
| tg_reply_kb($rows, $resize) | Builds a persistent bottom menu (Reply Keyboard). | $kb = tg_reply_kb([[['text'=>'Balance']]]); |
| tg_download_file($fileId) | Downloads any Telegram file to disk and returns its local file path. | $info = tg_download_file($fileId); |

#### 2. Core Messaging Engine: tg_send & tg_edit

The primary workhorse for communicating with Telegram users is `tg_send()`. It defaults to **HTML parse mode** with link previews disabled, which is the industry standard for clean bot UIs:

```php

```

 
 
  **Automatic Fallback Parsing**

  If your HTML contains malformed tags or entities that Telegram rejects (such as unescaped < or > characters), Botlify Cloud's `tg_api` engine automatically retries once as plain text so your bot never crashes or drops messages.
 

#### 3. Building Interactive Keyboards & Menus

Constructing multi-dimensional keyboard arrays in pure PHP is traditionally tedious. Botlify Cloud simplifies button construction into single-line calls:

```php

```

##### Persistent Bottom Reply Keyboards

For persistent custom keyboards docked above the user's mobile keyboard input:

```php

```

#### 4. Handling Button Clicks: tg_answer_cb

When a user taps an inline callback button, Telegram displays a spinning loading icon on the button until your bot answers the query. Failing to answer within 3 seconds causes the button to show a network timeout error.

Use `tg_answer_cb()` immediately upon receiving a `callback_query`:

```php

```

#### 5. Channel Membership Verification: tg_is_member

Force-subscribing users to your announcements channel before allowing them to access bot features is one of the most common Telegram bot patterns. `tg_is_member()` handles the `getChatMember` API call, inspects the status string (`creator`, `administrator`, `member`), and returns a clean boolean (`true` or `false`):

```php

```

#### 6. Sending Photos, Documents & Media: tg_send_media

`tg_send_media()` handles both remote HTTP URLs and local files on the Botlify Cloud SSD drive. When a local file path is given, it automatically creates a `CURLFile` object with proper MIME-type headers:

```php

```

#### 7. Downloading Telegram Files to Disk: tg_download_file

When users send photos, voice notes, documents, or video files to your bot, Telegram provides a `file_id`. `tg_download_file()` automatically queries `getFile`, resolves Telegram's file server URL, streams the bytes into a temporary directory on the cloud drive, and returns the absolute local path:

```php

```

#### 8. Complete Production Blueprint Using Native Helpers

Here is a complete, self-contained, copyable `index.php` that demonstrates how all `tg_*` helpers connect in a production bot:

```php

```

---

### 14.5. [Getting Started] Configuring @BotFather

> Complete guide to setting bot profile photo, descriptions, slash commands, and privacy settings.

#### Essential @BotFather Commands

   

Telegram's official `@BotFather` provides extensive settings to brand and configure your bot. Here is the master command cheatsheet:

   
    
| Command | Purpose | Example / Usage |
| --- | --- | --- |
| /setname | Changes the public display name of your bot. | Botlify Demo Bot |
| /setdescription | Sets the text shown on the empty chat screen before pressing Start. | Introduces features and why users should tap Start. |
| /setabouttext | Sets the bio shown on the bot's profile card. | Brief 120-character summary. |
| /setuserpic | Uploads the avatar profile picture for your bot. | Send a high-resolution square image. |
| /setcommands | Registers the slash command autocomplete popup. | start - Launch bot help - Support |
| /setjoingroups | Controls whether your bot can be added to Telegram groups. | Enable or Disable. |
| /setprivacy | Toggles group privacy mode (receive all messages vs mentions only). | Disable if your bot must read all group chat text. |

   

   
> [!NOTE]
> **Automated Command Registration**
> Botlify bots automatically call setMyCommands and setChatMenuButton on startup, so your slash commands and blue [Menu] button are configured automatically without manual setup!

---

### 14.6. [Getting Started] Obtaining Telegram Admin Chat ID

> How to find your numeric User ID and link it to your Botlify account for full administrative control.

#### Why is Admin Chat ID Required?

   

In Telegram, every account has a permanent numeric identifier (e.g. `5839201472`). Unlike usernames (which can be changed anytime), numeric IDs never change.

   

Botlify injects your `ADMIN_CHAT_ID` into your bot's `.env` file. When an incoming message arrives, your bot compares `$from['id'] === ADMIN_CHAT_ID` to grant privileged admin powers, such as:

   
    
- Broadcasting messages to all bot users.

    
- Viewing financial withdrawals, balances, and system stats.

    
- Approving or rejecting user tasks.

    
- Accessing hidden administrative slash commands (e.g. `/admin`, `/stats`).

   

   

#### How to Find Your Numeric ID

   
    
- Open Telegram and search for [@chat_id_echo_bot](https://t.me/chat_id_echo_bot) or [@userinfobot](https://t.me/userinfobot).

    
- Send `/start`.

    
- The bot will reply with your exact numeric ID (e.g. `Your ID: 5839201472`).

    
- Copy this number, visit your **Account & API Key** tab in Botlify Dashboard, and paste it into **Telegram Admin ID**.

---

### 14.7. [Bot Studio & Development] Botlify Cloud Runtime: .env, database.db & error.log

> The complete runtime reference: auto-injected .env credentials (BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME), the private database.db (SQLite WAL), error.log diagnostics, and sandbox compliance rules.

Every bot on Botlify Cloud runs inside an isolated sandbox with a fixed set of auto-injected credentials, a private SQLite database, and a dedicated error log. These are the only runtime resources you need — no configuration files to create, no secrets to manage.

#### Auto-Injected .env Variables

Botlify Cloud provisions three locked environment variables in every bot's `.env` file. They are injected automatically — **never hardcode them** in your code. Always load them with `getenv()`:

| Variable | Type | Description |
| --- | --- | --- |
| BOT_TOKEN | String | Active Telegram Bot API token from @BotFather. Used internally by the bot() helper — you only need it for raw cURL calls. |
| ADMIN_CHAT_ID | Integer | Numeric Telegram user ID of the bot administrator/owner. Perfect target for quick tests, alerts, and admin notifications. |
| BOT_USERNAME | String | Public bot username without the leading @ (e.g. MySuperBot). |

```php

```

> [!WARNING]
> **Never Hardcode Secrets**
> Writing '123456:ABC-DEF...' directly in your code is a security violation. Always read credentials with getenv() — the sandbox and code auditor reject hardcoded tokens.

#### Main Database: database.db

Each bot ships with a private SQLite database at `database.db` in the bot's root directory, automatically running in **WAL (Write-Ahead Logging) mode** for fast concurrent reads and writes. Connect with PDO:

```php

```

Manage the same `database.db` visually with [SQLite 3 Studio & Data Explorer](/sqlite-studio), and query it remotely via the REST API (`action=db_query`).

#### Error Log: error.log

All runtime errors, webhook failures, and anything you write with `error_log()` land in `error.log` inside the bot's root directory. Read it three ways:

```php

```

```php
GET https://botlify.cloud/user_api.php?action=read_file&bot_id=&file=error.log
X-API-KEY:
```

> [!NOTE]
> **Pro Tip**
> Wrap error.log tails in <code> or a <pre> block when sending them to Telegram — log output often contains characters Telegram would otherwise parse as formatting.

#### Sandbox Compliance Cheat Sheet

All code runs inside the [Per-Bot Security Sandbox](/security-sandbox). Keep this cheat sheet next to you while coding:

| Status | Pattern | Examples |
| --- | --- | --- |
| Allowed | Markdown & SQL backticks in strings | "Use `help` to start", SELECT `id` FROM `users` |
| Allowed | Object method calls, modular includes | $pdo->exec(), require_once __DIR__ . '/config.php' |
| Allowed | Native PHP extensions | pdo_sqlite, curl, json, mbstring |
| Blocked | Shell execution | exec(), shell_exec(), system(), passthru(), proc_open(), popen(), backtick operator |
| Blocked | Dynamic evaluation | eval(), assert(), create_function() |
| Blocked | Paths outside the bot workspace & platform internals | /etc/passwd, platform config files, fbh_pdo() |

#### Quick Checklist

- Load credentials with `getenv('BOT_TOKEN')`, `getenv('ADMIN_CHAT_ID')`, `getenv('BOT_USERNAME')` — never hardcode.

- Store data in `database.db` with PDO + WAL — it is private to your bot.

- Write diagnostics with `error_log()` — they appear in `error.log`.

- Send alerts and test messages to `$ADMIN_CHAT_ID`.

- No Composer, no shell functions, no eval — stay sandbox-compliant.

---

### 14.8. [Bot Studio & Development] Code Studio & Web IDE

> Edit multi-file codebases in real-time with syntax highlighting, automatic linting, and zero deployment latency.

#### The In-Browser Cloud IDE

   

Botlify includes a full-featured web code editor located in **Bot Studio → Code Editor**. You can view, create, edit, and organize multiple files right from your browser or mobile device.

   

#### Key Studio Features

   
    
- **Multi-File Project Support:** Create modular projects with helper files (e.g. `includes/database.php`, `handlers/callback.php`).

    
- **Real-Time Syntax Validation:** Before saving, Botlify runs strict PHP syntax checks. If a parse or syntax error is found, it warns you immediately to prevent breaking live production webhooks.

    
- **Zero-Restart Hot Reloading:** Changes saved to `index.php` are active immediately on the next incoming Telegram update. No server restarts or redeployment delays required!

   

   

#### Standard Starter Template Structure

   
```php

```

  
   

#### Platform Auto-Injected System Environment Variables (.env)

   

When you deploy or manage a bot on **Botlify Cloud**, the platform automatically provisions an isolated `.env` file in your bot's root directory. You never need to hardcode sensitive tokens or IDs directly into your PHP scripts.

   
> [!TIP]
> **The 3 Locked Core System Variables**
> Botlify Cloud automatically synchronizes and locks these three variables with the platform database:
>      
>       BOT_TOKEN — The unique Telegram Bot API token issued by @BotFather.
>       ADMIN_CHAT_ID — The numeric Telegram Chat ID of the bot administrator/owner used for /admin access.
>       BOT_USERNAME — The public Telegram username of the bot (without the @ prefix).

   
    
| Variable Name | Sample Value | Platform Behavior & Usage in PHP |
| --- | --- | --- |
| BOT_TOKEN | 7123456789:AAHq_EXAMPLE_TOKEN... | Auto-injected from your BotFather token. Used by bot() helper to dispatch Telegram API requests. |
| ADMIN_CHAT_ID | 123456789 | Auto-injected from your Telegram numeric User ID. Checked on incoming updates to grant /admin and broadcast access. |
| BOT_USERNAME | MySuperBot | Auto-injected from Telegram. Used for dynamic referral links (e.g. https://t.me/MySuperBot?start=ref123). |

   

   

#### How to Read System Variables in index.php

   

Use this native, zero-dependency parser at the top of your `index.php`:

   
```php

```

---

### 14.9. [Bot Studio & Development] SQLite 3 Studio & Data Explorer

> Built-in zero-maintenance relational database engine with visual SQL query console and automatic WAL mode.

#### Zero-Maintenance Database Architecture

   

Every bot on Botlify Cloud comes pre-provisioned with its own dedicated SQLite 3 database located at `database.db`. Unlike MySQL or PostgreSQL, SQLite requires no external ports, usernames, or passwords. It operates at native memory speed right on high-speed NVMe SSDs.

   

#### Connecting via PDO in PHP

   
```php
$db = new PDO('sqlite:' . __DIR__ . '/database.db', null, null, [
    PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
]);

// Enable WAL Mode for High Concurrency
$db->exec("PRAGMA journal_mode = WAL;");
$db->exec("PRAGMA busy_timeout = 5000;");

// Create Standard Users Table
$db->exec("CREATE TABLE IF NOT EXISTS users (
    chat_id TEXT PRIMARY KEY,
    username TEXT,
    first_name TEXT,
    balance REAL DEFAULT 0.00,
    interactions INTEGER DEFAULT 1,
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP
);");
```

   

#### Using the Visual Database Studio

   

Inside **Bot Studio → Database**, you have access to:

   
    
- **Schema Explorer:** View all tables, column types, and primary keys.

    
- **Interactive SQL Console:** Run any query (`SELECT`, `INSERT`, `UPDATE`, `DELETE`, `ALTER TABLE`) with formatted result tables.

    
- **Live Data Browser:** Inspect user records, balances, and interaction logs with pagination and search.

---

### 14.10. [Bot Studio & Development] Automated Cron Scheduler

> Schedule background workers, reset daily rewards, and send automated notifications without external cron services.

#### Platform Cron Engine

   

Bots often need to execute background operations at recurring intervals — such as resetting daily login streaks at midnight, executing pending payouts, or cleaning up expired sessions.

   

Botlify includes a native Cron Scheduler running at 1-minute intervals. You can configure cron jobs directly in **Bot Studio → Variables & Cron**.

   

#### Supported Crontab Expressions

   
    
| Expression | Frequency | Description |
| --- | --- | --- |
| * * * * * | Every 1 Minute | Runs once every minute (minimum platform interval). |
| */5 * * * * | Every 5 Minutes | Standard for transaction monitoring and queue processing. |
| 0 * * * * | Hourly | Runs at minute 0 of every hour. |
| 0 0 * * * | Daily Midnight | Runs once per day at 00:00 UTC (ideal for daily bonus resets). |

   

   

#### Writing a Standalone Cron Script

   

Create a dedicated file such as `cron_worker.php` in your bot's folder:

   
   
```php

```

---

### 14.11. [Bot Studio & Development] Webhook Manager & Test Simulator

> Simulate Telegram webhook payloads, test logic in-browser, and inspect live execution errors.

#### The Test Simulator

   

Debugging webhook endpoints usually requires sending messages on Telegram and checking remote error logs. With Botlify's built-in **Webhook Test Simulator**, you can simulate updates instantly inside Bot Studio.

   

#### How Simulation Works

   
    
- Open **Bot Studio → Overview** or **Variables & Cron**.

    
- Click **Simulate /start Webhook**.

    
- Botlify sends an authentic Telegram update payload to your bot's `index.php` script via local execution.

    
- The simulator displays the full execution output, runtime duration, memory usage, and the last 10 lines of `error.log`.

   

   
> [!WARNING]
> **Inspect error.log Instantly**
> If your bot code throws a fatal exception or uncaught error, it is recorded in error.log. The studio flags the bot card with a red alert badge so you can resolve issues immediately.

---

### 14.12. [AI Agent & MCP Integration] Model Context Protocol (MCP) Server Integration

> Connect AI IDEs (Cursor, Claude Desktop, Windsurf, Antigravity) to Botlify Cloud via standard JSON-RPC 2.0 / MCP protocol.

#### What is the Botlify MCP Server?

   

The **Botlify Model Context Protocol (MCP) Server** (located at `https://botlify.cloud/mcp.php`) is a standardized, production-grade **JSON-RPC 2.0** server implementing the open **Model Context Protocol (spec 2024-11-05)**. It allows autonomous AI agents and modern AI IDEs (such as Cursor, Claude Desktop, Windsurf, Google Antigravity, and custom LLM workflows) to directly build, deploy, query, and monitor Telegram bots inside their isolated cloud sandboxes.

   
> [!TIP]
> **Key Server Specifications**
> • Endpoint URL: https://botlify.cloud/mcp.php
>      • Protocol Version: 2024-11-05 (JSON-RPC 2.0)
>      • Authentication: API Key via X-API-KEY header, Authorization: Bearer <key>, or ?key=<key>
>      • Capabilities: tools (37 tools), resources (live schemas/logs), prompts (guided audits)

   

#### Connecting Your AI IDE to Botlify Cloud

   
```php
{
  "mcpServers": {
    "botlify": {
      "url": "https://botlify.cloud/mcp.php",
      "headers": {
        "X-API-KEY": "YOUR_BOTLIFY_API_KEY"
      }
    }
  }
}
```

   
```php
{
  "mcpServers": {
    "botlify-cloud": {
      "command": "npx",
      "args": [
        "-y",
        "mcp-remote",
        "https://botlify.cloud/mcp.php?key=YOUR_BOTLIFY_API_KEY"
      ]
    }
  }
}
```

   

#### Supported MCP Primitives

   
    
| MCP Primitive | Protocol Method | Description & Available Resources |
| --- | --- | --- |
| Tools | tools/list, tools/call | 37 executable functions covering bot creation, deployment, file editing, SQLite queries, crons, broadcasts, and webhook tests. |
| Resources | resources/list, resources/read | Direct read access to real-time bot metadata, database schemas, and guides:                   fbh://docs/botmaking — Complete Bot Making Guide          fbh://bots/{id}/info — Bot runtime metadata          fbh://bots/{id}/schema — Live SQLite tables & columns          fbh://bots/{id}/env — Active environment variables |
| Prompts | prompts/list, prompts/get | Pre-configured AI assistant workflows:                   bot_health_check — Automated diagnostic suite          code_audit_and_enhance — Security & WAL optimization audit          create_styled_keyboard_bot — Scaffolds Telegram 8.0 styled bots          send_rich_broadcast — Universal broadcast composer |

   

   

#### Server Health & Diagnostic Metadata Endpoint

   

Sending a standard HTTP GET request to `mcp.php` returns connectivity status and verified user authentication metadata:

   
```php
{
  "server": "Botlify MCP Server",
  "protocolVersion": "2024-11-05",
  "status": "online",
  "authenticated_user": {
    "chat_id": "123456789",
    "username": "johndoe",
    "first_name": "John"
  },
  "capabilities": ["tools", "resources", "prompts"],
  "docs": "https://docs.botlify.cloud/?page=mcp-overview"
}
```

---

### 14.13. [AI Agent & MCP Integration] Complete MCP Tool Catalog (All 37 Tools)

> Detailed reference for every MCP tool exposed by Botlify Cloud for autonomous AI agents and code assistants.

#### Master Catalog: 37 MCP Tools

   

The Botlify MCP Server exposes **37 high-level tools** allowing AI models to perform end-to-end bot construction, SQLite operations, file manipulation, and automated testing.

   

#### 1. Bot Lifecycle & Management Tools

   
    
| Tool Name | Required Arguments | Optional Arguments | Behavior & Output |
| --- | --- | --- | --- |
| list_bots | None | status ("active" \| "deleted" \| "all") | Returns an array of bots with ID, username, webhook status, storage usage, and created date. |
| get_bot_info | bot_id | None | Detailed bot info including database size, file count, and crons. Accepts numeric ID or @username. |
| create_bot | token | admin_chat_id | Provisions a new bot sandbox, locks credentials in .env, registers live webhook, and creates SQLite database.db. |
| delete_bot | bot_id | permanent (bool) | Soft deletes to recycle bin by default; pass permanent=true to purge files and free the slot immediately. |
| restore_bot | bot_id | None | Recovers a bot from the recycle bin back to active status and resets webhook. |
| restart_bot | bot_id | None | Refreshes Telegram webhook registration, clears error flags, and re-syncs Telegram connection. |
| update_bot | bot_id | token, admin_chat_id | Updates BotFather token or owner chat ID in database and synchronizes .env. |

   

   

#### 2. File System & Code Editor Tools

   
    
| Tool Name | Required Arguments | Optional Arguments | Behavior & Output |
| --- | --- | --- | --- |
| list_files | bot_id | path | Lists all files and directories in bot root or subfolder with size, permissions, and modified timestamp. |
| read_file | bot_id | file (default: index.php) | Reads file contents. Protected files (e.g. .env) are safely masked. |
| write_file | bot_id, content | file (default: index.php) | Writes code to specified file inside the isolated bot workspace. |
| create_file | bot_id, name | path, content | Creates a new file in root or specified subfolder. |
| upload_file | bot_id, name, content | path, is_base64 (bool) | Uploads binary or text files (supports base64 encoding for images, SQLite backups, and assets). |
| create_folder | bot_id, name | path | Creates a new sub-directory inside the bot workspace. |
| delete_file | bot_id, file | None | Deletes a file. System files (.env, database.db) are protected against accidental deletion. |

   

   

#### 3. Environment Variables (.env) Tools

   
    
| Tool Name | Arguments | Behavior |
| --- | --- | --- |
| get_env_variables | bot_id | Returns parsed key-value array and raw text of the bot's .env file. |
| set_env_variables | bot_id, variables (array or string) | Bulk overwrites or updates custom environment variables while protecting locked system vars. |
| set_env_variable | bot_id, key, value | Sets or updates a single environment variable key-value pair. |
| delete_env_variable | bot_id, key | Removes a custom environment variable. Locked system vars (BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME) cannot be deleted. |

   

   

#### 4. Automated Cron Scheduler Tools

   
    
| Tool Name | Arguments | Behavior |
| --- | --- | --- |
| list_cron_jobs | bot_id | Lists all scheduled workers, intervals (e.g. * * * * *), active status, and last execution logs. |
| create_cron_job | bot_id, name, schedule, command | Registers a new recurring background worker down to 1-minute intervals. |
| run_cron_job | bot_id, cron_id | Manually triggers an immediate execution of the cron worker and returns execution stdout/stderr. |

   

   

#### 5. SQLite Database Explorer Tools

   
    
| Tool Name | Arguments | Behavior |
| --- | --- | --- |
| get_database_schema | bot_id | Returns table list, column names, data types, indexes, and total database size on disk. |
| query_database | bot_id, query | Executes SQL query on the bot's local database.db and returns formatted rows. |

   

   

#### 6. Universal Broadcast Studio Tools

   
    
| Tool Name | Arguments | Behavior |
| --- | --- | --- |
| get_broadcast_stats | bot_id | Returns total subscribers in database.db, active users, and delivery telemetry. |
| send_broadcast | bot_id, message, options | Initiates a rate-limited mass broadcast to all bot users with customizable call-to-action buttons. |

   

   

#### 7. User Profile & Account Tools

   
    
| Tool Name | Arguments | Behavior |
| --- | --- | --- |
| get_profile | None | Returns user Telegram ID, username, plan tier, bot quota limit, and account stats. |

   

   

#### 8. Bot Code Transfer System Tools

   
    
| Tool Name | Arguments | Behavior |
| --- | --- | --- |
| create_bot_transfer | bot_id, target_recipient | Generates a cryptographic 6-digit transfer code to securely hand off bot ownership. |
| list_bot_transfers | None | Lists all pending incoming and outgoing transfers with expiration countdowns. |
| get_transfer_info | transfer_code | Inspects transfer details, bot name, and target recipient before claiming. |
| accept_bot_transfer | transfer_code, token, admin_chat_id | Claims transferred bot into recipient's account with new BotFather credentials. |
| reject_bot_transfer | transfer_id | Cancels or rejects an active transfer request. |

   

   

#### 9. Bot Building, Validation & Webhook Simulation Tools

   
    
| Tool Name | Arguments | Behavior |
| --- | --- | --- |
| get_bot_making_guide | section (optional) | Fetches official Botlify architectural instructions and best practice patterns. |
| scaffold_bot_code | type, bot_name | Generates boilerplate starter templates (e.g. styled_keyboard, store_bot, fsm_form). |
| install_bot_scaffold | bot_id, type | Directly writes a verified starter template into the bot's index.php. |
| validate_bot_code | code | Dual-engine PHP syntax parser and linter. Guarantees 0 syntax errors before file writes. |
| test_bot_webhook | bot_id, update (optional) | Simulates an incoming Telegram update (default: /start) and captures output/errors without sending live Telegram messages. |
| build_and_deploy_bot | bot_id, code | The Ultimate All-in-One Deployment Tool: Validates PHP syntax, writes to index.php, simulates webhook execution, and returns production status. |

---

### 14.14. [Storage & Architecture] Dedicated Per-Bot Storage Architecture

> Understanding Botlify's isolated storage quota model and NVMe SSD sandbox limits.

#### Independent Per-Bot Quotas

   

In Botlify Cloud, storage limits are **allocated individually per bot**, not shared across your entire fleet.

   
   
> [!NOTE]
> **Default Quota: 15 MB Per Bot**
> If you have 10 bots, you receive 10 separate 15 MB environments (totaling 150 MB across your fleet). Each bot operates with its own file and database limits independently.

   

#### What Counts Towards Bot Storage?

   
    
- **PHP Source Code & Assets:** `index.php`, custom scripts, helper classes, icons, or JSON files.

    
- **SQLite Database:** The file size of `database.db` and its temporary WAL journal files.

    
- **Error Logs:** Output recorded in `error.log`.

   

   

#### Upgrading Storage Quotas

   

Need more storage for media-heavy bots or large SQLite databases? You can expand your per-bot quota by:

   
    
- **Inviting Referrals:** Every active referral adds extra storage and bot slots to your account.

    
- **Contacting Support:** Administrators can assign custom high-capacity quotas (50 MB, 100 MB, 500 MB+) per user or per bot.

---

### 14.15. [AI Agent & MCP Integration] Autonomous AI Bot Building Guide

> How to prompt AI assistants to build, test, and deploy Telegram bots with zero syntax errors.

#### The Zero-Error Deployment Pipeline

   

When interacting with AI models through Botlify's MCP Server, AI agents follow a strict 4-step deployment cycle:

   
    
- **Retrieve Platform Context:** The agent calls `get_bot_making_guide` to access the 50-section Telegram Bot API master guide and scaffold rules.

    
- **Generate Modular Code:** The agent constructs code using strict types, cURL dispatchers, and SQLite WAL database storage.

    
- **Pre-Deployment Lint Check:** Before writing to disk, the agent or platform runs `php -l` syntax validation. If any syntax error exists, the deployment is blocked.

    
- **Webhook Test Simulation:** The agent executes `test_bot_webhook` to simulate an incoming `/start` message and verify that stdout is clean and `error.log` has no fatal exceptions.

   

   

#### Sample Prompt for AI Assistants

   
```php
"Use Botlify MCP tools to inspect my bot @my_demo_bot.
Build a complete Refer-to-Earn bot with:
1. Daily claim reward ($0.50 / 24h)
2. Referral system ($1.00 / invite) with dynamic links
3. SQLite users and transactions schema
4. Native /start, /balance, /help slash commands and Telegram [Menu] button
5. Message reactions (👍, 🔥) and typing indicators
Validate the code syntax, write it to index.php, and run test_bot_webhook to verify."
```

  
   

#### Zero-Error AI Prompting Standard for Botlify Runtime

   

Botlify Cloud is built around the **Botlify Native PHP 8.2+ Runtime**. When generating bots using AI tools like **Cursor, Windsurf, Claude 3.7 Sonnet, ChatGPT 4o, or Google Gemini**, always feed the AI our standardized rules to guarantee zero deployment errors:

   
    
| Runtime Rule | Requirement | Why It Prevents Errors |
| --- | --- | --- |
| Pure Native PHP | Single-file index.php, zero Composer dependencies | Eliminates Class not found and missing vendor directory crashes. |
| Primary DB | Strictly __DIR__ . '/database.db' | Integrates natively with Botlify's built-in SQLite Studio and automated backups. |
| Runtime Logs | Strictly __DIR__ . '/error.log' | All exceptions are captured in Botlify's real-time Web IDE log viewer. |
| Fast HTTP 200 | http_response_code(200); | Prevents Telegram webhook retry storms that exhaust server CPU. |
| Callback Dismissal | tg('answerCallbackQuery', ...) | Immediately removes the user's loading clock spinner on inline button clicks. |

   

   

#### Master Universal Prompt (Feed to AI Along With Docs)

   
```php
Read the documentation at https://docs.botlify.cloud/llms.txt.
You must generate a single-file index.php for Botlify Cloud:
- Native PHP 8.2+ only, zero Composer dependencies.
- SQLite database MUST be __DIR__ . '/database.db' with WAL mode.
- Error log MUST be __DIR__ . '/error.log'.
- Use persistent cURL for Telegram API (20ms latency).
- Answer callback queries immediately.
- Wrap all update logic in try...catch(Throwable $e) logging to error.log and returning HTTP 200.

Create a complete Telegram bot with the following features:
[INSERT YOUR BOT REQUIREMENTS HERE]
```

---

### 14.16. [REST API Reference] REST API Overview, Authentication & Security

> Unified developer endpoint at user_api.php with rate limiting, HTTPS enforcement, OAuth token introspection, and authentication methods.

#### Developer REST API Overview (user_api.php)

   

The **Botlify Developer REST API** is unified under a single high-performance endpoint: `https://botlify.cloud/user_api.php`. It accepts both HTTP GET and POST requests (URL-encoded form data or `application/json` payloads) to manage all user resources programmatically.

   

#### 1. The 4 Authentication Mechanisms

   

Authenticate requests using any of the following 4 methods:

   
    
| Method | Format | Example Header / Parameter |
| --- | --- | --- |
| X-API-KEY Header (Recommended) | HTTP Request Header | X-API-KEY: botlify_usr_98a72b1... |
| Bearer Token | HTTP Authorization Header | Authorization: Bearer botlify_usr_98a72b1... |
| URL Query Parameter | GET Query String | ?api_key=botlify_usr_98a72b1... or ?key=... |
| JSON / Form Body | POST Request Body | {"api_key": "botlify_usr_98a72b1...", "action": "list_bots"} |

   

   

#### 2. Strict Transport Security & Rate Limiting

   
    
- **HTTPS Enforcement:** All non-HTTPS requests are automatically redirected via HTTP 301 to `https://botlify.cloud/user_api.php` with HSTS enabled.

    
- **Sliding Window Rate Limiter:** Allows up to **60 requests per minute** per user account with burst allowances. If exceeded, returns HTTP 429 Too Many Requests with `Retry-After` headers.

   

   
```php
HTTP/2 200 OK
Content-Type: application/json; charset=utf-8
Strict-Transport-Security: max-age=31536000; includeSubDomains; preload
X-RateLimit-Limit: 60
X-RateLimit-Remaining: 58
X-RateLimit-Reset: 1774312800
RateLimit-Remaining: 58
```

   

#### 3. System Health & Public Unauthenticated Endpoints

   
    
| Action Name | Auth Required? | Purpose & Output |
| --- | --- | --- |
| action=ping | Yes | Returns {"ok": true, "message": "pong", "timestamp": 1774312800} |
| action=public_links | No (Public) | Returns official support, community group, and announcement channel links. |
| action=token | Yes | Generates OAuth 2.0 Bearer token payload with scope="mcp:read mcp:write mcp:tools mcp:full". |
| action=introspect | Yes | Introspects current API token validity and active scope. |

---

### 14.17. [REST API Reference] User Profile & Account APIs

> Retrieve account quotas, bot slots, Telegram ID, per-bot storage limits, and referral links.

#### Get User Profile & Account Quotas

   

Action: `get_profile` or `profile` or `me`

   
```php
curl -X POST https://botlify.cloud/user_api.php   -H "X-API-KEY: YOUR_API_KEY"   -H "Content-Type: application/json"   -d '{"action": "get_profile"}'
```

   

Returns complete account details: `chat_id`, `username`, `first_name`, `email`, `bot_limit`, `used_bots`, `available_slots`, `storage_mb` (per-bot quota), and `refer_link`.

---

### 14.18. [REST API Reference] Bot Management REST APIs (A-Z)

> Provision, delete, restore from recycle bin, restart, toggle webhooks, and inspect live Telegram webhook diagnostics.

#### Bot Management Actions in user_api.php

   

Manage the full lifecycle of your Telegram bots remotely using standard HTTP GET and POST requests:

   
    
| Action | Parameters | Description |
| --- | --- | --- |
| list_bots | status (active \| deleted \| all) | Returns array of all bots. By default filters out recycle bin bots. |
| get_bot | bot_id | Returns complete bot configuration, memory usage, webhook URL, and database size. |
| create_bot | token, admin_chat_id | Creates a new bot instance, locks credentials in .env, registers webhook with Telegram, and initializes database.db. |
| delete_bot | bot_id, permanent (bool) | Soft deletes to recycle bin by default; pass permanent=1 to permanently erase files and free bot slot. |
| restore_bot | bot_id | Restores a soft-deleted bot from the recycle bin and re-establishes live webhook. |
| restart_bot | bot_id | Refreshes webhook with Telegram, clears error state, and restarts bot execution sandbox. |
| toggle_webhook | bot_id, action_type (start \| stop \| toggle) | Enables or disables live webhook delivery on Telegram servers without deleting bot. |
| webhook_info | bot_id | Directly queries Telegram's official getWebhookInfo API and returns pending update counts and last error timestamps. |
| update_bot | bot_id, token, admin_chat_id | Updates bot credentials and synchronizes .env. |

   

   

#### Sample cURL Commands

   
```php
curl -X POST https://botlify.cloud/user_api.php \
  -H "X-API-KEY: YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "action": "create_bot",
    "token": "7123456789:AAHq_EXAMPLE_TOKEN",
    "admin_chat_id": "123456789"
  }'
```

   
```php
curl "https://botlify.cloud/user_api.php?action=webhook_info&bot_id=12&api_key=YOUR_API_KEY"
```

---

### 14.19. [REST API Reference] Bot Code Transfer System (A-Z)

> Securely transfer bot source code and architecture between Botlify users with automatic credential sanitization.

#### How Bot Transfer Works

   

The Bot Transfer Engine allows developers to clone and transfer bot projects to clients or other developers safely. Sensitive credentials (`.env` tokens and live `database.db`) are automatically sanitized and kept private.

   

#### 1. Create Transfer Offer (create_transfer)

   

Action: `create_transfer`

   Parameters: `bot_id`, `target_recipient` (Telegram `@username` or numeric ID)

   
```php
curl -X POST https://botlify.cloud/user_api.php   -H "X-API-KEY: YOUR_API_KEY"   -H "Content-Type: application/json"   -d '{
    "action": "create_transfer",
    "bot_id": 14,
    "target_recipient": "@client_username"
  }'
```

   

Returns a secure 72-hour transfer code: `{"ok": true, "transfer_code": "TR-14-8F92A1BC"}`.

   

#### 2. List Pending Transfers (list_transfers)

   

Action: `list_transfers` or `transfers`

   Returns incoming offers awaiting your acceptance as well as outgoing offers you created.

   

#### 3. Inspect Transfer Details (get_transfer)

   

Action: `get_transfer`

   Parameters: `transfer_code`

   Returns the bot display name, code file count, sender handle, and expiration timestamp.

   

#### 4. Accept Bot Transfer (accept_transfer)

   

Action: `accept_transfer`

   Parameters:

   
    
- `transfer_code`: The transfer verification code (e.g. `TR-14-8F92A1BC`).

    
- `token`: Recipient's new Telegram BotFather token.

    
- `admin_chat_id` (optional): Recipient's admin chat ID.

   
   
```php
curl -X POST https://botlify.cloud/user_api.php   -H "X-API-KEY: RECIPIENT_API_KEY"   -H "Content-Type: application/json"   -d '{
    "action": "accept_transfer",
    "transfer_code": "TR-14-8F92A1BC",
    "token": "7987654321:AAHnew_recipient_token..."
  }'
```

   

#### 5. Reject Bot Transfer (reject_transfer)

   

Action: `reject_transfer`

   Parameters: `transfer_id` (Numeric ID from `list_transfers`).

---

### 14.20. [REST API Reference] File System & Code Editor REST APIs

> Inspect directories, read/write index.php, upload binary assets via base64 or multipart form, create folders, and lint PHP code.

#### File System Actions in user_api.php

   

Each bot hosted on Botlify Cloud operates within an isolated dedicated directory. You have complete programmatic control over file creation, editing, uploading, and syntax validation:

   
    
| Action | Parameters | Description |
| --- | --- | --- |
| list_files | bot_id, path (optional) | Returns array of files and folders with size, type, and modified time. |
| read_file | bot_id, file (default: index.php) | Reads file contents. Protected files (.env) have secrets masked. |
| write_file / save_code | bot_id, file, content | Overwrites file contents inside the bot sandbox. |
| create_file | bot_id, path, name, content | Creates a new file in specified folder. |
| upload_file | bot_id, path, name, content, is_base64 (bool) | Uploads binary or text files. Supports base64 encoding or standard multipart form uploads ($_FILES['file']). |
| create_folder | bot_id, path, name | Creates a new subfolder in the bot's workspace. |
| delete_file | bot_id, file | Deletes specified file. Protected system files cannot be deleted. |
| rename_file | bot_id, old_path, new_name | Renames or moves a file within the bot directory. |
| validate_code / lint | code | Runs high-speed token parser and PHP linter on code string without saving. |

   

   
```php

```

---

### 14.21. [REST API Reference] Environment Variables (.env) APIs

> Manage bot environment variables, API secrets, and configuration keys securely.

#### 1. Get Environment Variables (get_env)

   

Action: `get_env`

   Parameters: `bot_id`

   Returns a key-value dictionary of environment variables.

   

#### 2. Set Single Variable (set_env_variable)

   

Action: `set_env_variable` or `set_env_var`

   Parameters: `bot_id`, `key`, `value`

   
```php
curl -X POST https://botlify.cloud/user_api.php   -H "X-API-KEY: YOUR_KEY"   -H "Content-Type: application/json"   -d '{
    "action": "set_env_variable",
    "bot_id": 14,
    "key": "PAYMENT_API_KEY",
    "value": "sk_live_9876543210"
  }'
```

   

#### 3. Delete Variable (delete_env_variable)

   

Action: `delete_env_variable`

   Parameters: `bot_id`, `key`

---

### 14.22. [REST API Reference] Automated Cron Scheduler REST APIs

> Schedule recurring tasks, pause/resume workers, trigger immediate manual runs, and inspect execution logs.

#### Cron Actions in user_api.php

   

Automate background workers (e.g. daily resets, subscription checks, database cleanups) down to 1-minute intervals:

   
    
| Action | Parameters | Description |
| --- | --- | --- |
| list_crons | bot_id | Returns array of cron jobs with schedule string, active status, last execution, and logs. |
| create_cron | bot_id, name, schedule, command | Creates a recurring background worker. Schedule accepts standard 5-part cron syntax (e.g. */15 * * * *). |
| toggle_cron | bot_id, cron_id | Pauses or resumes an active cron worker without deleting it. |
| run_cron | bot_id, cron_id | Immediate Manual Trigger: Executes the cron job immediately and returns stdout/stderr logs. |
| delete_cron | bot_id, cron_id | Permanently deletes the scheduled cron worker. |

---

### 14.23. [REST API Reference] SQLite Database Operations APIs

> Query bot SQLite databases remotely with parameterized queries and schema inspection.

#### 1. Database Schema & Info (db_info)

   

Action: `db_info`

   Parameters: `bot_id`

   Returns database file size, SQLite version, journal mode (WAL), table names, schemas, and row counts.

   

#### 2. Run SQL Query (db_query)

   

Action: `db_query`

   Parameters: `bot_id`, `query` (SQL statement), `params` (optional array of prepared statement values)

   
```php
curl -X POST https://botlify.cloud/user_api.php   -H "X-API-KEY: YOUR_KEY"   -H "Content-Type: application/json"   -d '{
    "action": "db_query",
    "bot_id": 14,
    "query": "SELECT chat_id, username, balance FROM users WHERE balance > ? ORDER BY balance DESC LIMIT 10",
    "params": [5.0]
  }'
```

   

Supports `SELECT`, `INSERT`, `UPDATE`, `DELETE`, and `CREATE TABLE` statements.

---

### 14.24. [REST API Reference] Mass Broadcast & Telemetry APIs

> Send high-speed mass broadcasts to all bot subscribers with inline buttons and delivery stats.

#### 1. Broadcast Audience Stats (broadcast_stats)

   

Action: `broadcast_stats`

   Parameters: `bot_id`

   Returns total subscribers and active user counts in the bot database.

   

#### 2. Dispatch Broadcast (send_broadcast)

   

Action: `send_broadcast`

   Parameters:

   
    
- `bot_id`: Target bot ID

    
- `message`: HTML or Markdown formatted text

    
- `audience`: `all` or `active7d` (active in last 7 days)

    
- `photo_url` (optional): Image URL to attach

    
- `keyboard` (optional): Inline button grid

   
   
```php
curl -X POST https://botlify.cloud/user_api.php   -H "X-API-KEY: YOUR_KEY"   -H "Content-Type: application/json"   -d '{
    "action": "send_broadcast",
    "bot_id": 14,
    "message": "🔥 Special Announcement!
New features are live.",
    "audience": "all"
  }'
```

---

### 14.25. [REST API Reference] Scaffolding, Validation & Webhook Testing APIs

> Dual-engine syntax validation, all-in-one build_and_deploy_bot pipeline, and webhook simulator with stdout/stderr capture.

#### AI Bot Building & Testing Actions in user_api.php

   

Botlify Cloud includes built-in endpoints for autonomous bot generation, syntax verification, and testing simulated Telegram updates without sending live messages:

   
    
| Action | Parameters | Description |
| --- | --- | --- |
| build_and_deploy_bot | bot_id, code, options | The Ultimate Deploy Pipeline: Validates PHP syntax, writes code to index.php, simulates incoming webhook execution, and returns production status. |
| validate_code | code | Dual-engine PHP syntax validation (token analyzer + linter). Returns {"ok": true, "valid": true} or exact line and error message. |
| test_webhook | bot_id, update (optional) | Simulates an incoming Telegram update (default: /start message). Executes bot code inside sandbox and captures all stdout, stderr, and HTTP response codes. |
| scaffold_bot | type, bot_name | Returns verified PHP code boilerplate for specified archetype (e.g. styled_keyboard, store_bot, fsm_form). |
| install_scaffold | bot_id, type | Installs specified starter template directly into bot's index.php. |
| bot_making_docs | section (optional) | Fetches structured Botlify Cloud bot making documentation and architectural rules. |

   

   
```php
curl -X POST https://botlify.cloud/user_api.php \
  -H "X-API-KEY: YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "action": "test_webhook",
    "bot_id": 12,
    "update": {
      "update_id": 999999,
      "message": {
        "message_id": 1,
        "from": {"id": 123456789, "first_name": "Tester"},
        "chat": {"id": 123456789, "type": "private"},
        "date": 1774312800,
        "text": "/start"
      }
    }
  }'
```

---

### 14.26. [Storage & Architecture] Anti-Flood & Rate Limiting Rules

> How Botlify Cloud protects your bots against spam, DoS attacks, and high traffic spikes.

#### Built-in Protection Engines

   

Telegram webhooks can experience sudden surges in traffic during mass marketing campaigns or spam attacks. Botlify employs multi-tier traffic filtering:

   
    
- **Per-IP & Per-User Throttling:** Spammers sending more than 30 messages per second from a single chat are automatically queued or dropped.

    
- **Cloudflare DDoS Shielding:** High-bandwidth volumetric attacks are absorbed before reaching backend PHP workers.

    
- **Memory Isolation:** Memory limits (128 MB per request) prevent runaway scripts from affecting other bots on the node.

---

### 14.27. [Troubleshooting & Support] Troubleshooting & Error Diagnostics

> Common errors, how to read error.log, and fixing webhook handshake issues.

#### 1. The Bot Does Not Respond to /start

   

If your bot is not replying to messages, check these 3 common causes:

   
    
- **Check Webhook Status:** Ensure the status badge in Bot Studio displays ACTIVE. If paused, click **Re-Sync Webhook**.

    
- **Syntax Errors:** Check **Error Logs** in Bot Studio. A missing semicolon or typo in PHP will cause an immediate fatal error.

    
- **Run Webhook Simulator:** Click **Simulate /start** in Bot Studio to see the exact PHP output and stack trace.

   

   

#### 2. Telegram cURL Timeouts

   

Always keep Telegram API cURL timeouts reasonable (10–15 seconds). Never execute heavy blocking operations (like large external web scrapes) synchronously inside the webhook handler; instead, delegate them to background cron jobs.

   

#### 3. Official Support

   

Need personalized help from the Botlify engineering team? Reach us via:

   
    
- **Telegram Support:** [@botlify_support](https://t.me/botlify_support)

    
- **Official Channel:** [@BotlifyOfficial](https://t.me/BotlifyOfficial)

   
  
   

#### Troubleshooting: Connection Timed Out After 5001 Milliseconds

   

**Cause:** A strict 5-second cURL connection timeout (`CURLOPT_CONNECTTIMEOUT => 5`) causes outgoing calls to `api.telegram.org` to abort during temporary network latency spikes or TCP SYN retransmissions.

   

**Solution:** In `includes/telegram.php` and your bot's `bot()` cURL wrapper, configure `CURLOPT_CONNECTTIMEOUT => 8` or `10` and `CURLOPT_TIMEOUT => 15` or `20`. Additionally, implement socket auto-reset (`$ch = null;`) on error so stale connections are never reused.

   

#### Troubleshooting: Security Sandbox Violation (Backtick Operator)

   

**Cause:** Older sandbox engines mistakenly flagged backticks inside Telegram Markdown strings (e.g., `"Your ID is `123`"`) or MySQL queries as shell execution operators.

   

**Solution:** The Botlify Sandbox now utilizes native PHP tokenization (`token_get_all`), ensuring that string literals containing backticks and Telegram commands such as `/home` are recognized as safe and permitted.

---

### 14.28. [AI Agent & MCP Integration] AI Bot Architects: Google Gemini Gem, ChatGPT Custom GPT & Claude

> Deploy autonomous AI bot maker companions in Google Gemini, ChatGPT, and Claude with 1-click copyable system instructions.

#### AI Bot Architects: Google Gemini Gem, ChatGPT Custom GPT & Claude

Transform your favorite AI models into **Senior Telegram Bot Architects** tailored exclusively for the Botlify Cloud serverless runtime. These pre-tuned system instructions empower **Google Gemini, OpenAI ChatGPT, and Anthropic Claude** to autonomously brainstorm, write, and verify complete, 100% bug-free `index.php` bots with SQLite WAL storage, self-healing migrations, and in-Telegram admin suites.

> [!TIP]
> **Dual-Mode Autonomous Intelligence & Multilingual Fluency**
> The AI operates with intelligent context awareness: when asked questions or given error traces, it mentors casually without dumping unwanted code; when asked to build a bot, it autonomously brainstorms the complete user journey, FSM multi-turn forms, and outputs a complete, production-ready index.php script in fluent English, Bengali, or any language.

##### Option 1: Google Gemini Gem ("Botlify Supreme AI Engine")

Deploy this prompt inside **Google Gemini Advanced (Gem Manager)** or **Google AI Studio** to create a dedicated Botlify Bot Maker Gem.

 
  **Step 1:** Open [Google Gemini](https://gemini.google.com/) → Click **Gem Manager** → **New Gem**.
 
 
  **Step 2:** Set Gem Name to `Botlify Supreme AI Engine & Bot Architect`.
 
 
  **Step 3:** Click **Copy Prompt** on the card below and paste into the **Instructions** field.
 

#### AI Master Prompt: Google Gemini Gem Instructions

```text
You are "Botlify Supreme AI Engine & Master Bot Architect", the official intelligent AI companion, global engineering advisor, and Principal Telegram Bot Architect for Botlify Cloud (https://botlify.cloud).

You are warm, empathetic, ultra-smart, and universally multilingual. You speak, read, and write in ANY language in the world with native fluency (English, Bengali, Spanish, Hindi, Arabic, Russian, Portuguese, French, German, Indonesian, Turkish, etc.). You converse naturally with users, answer questions, debug errors, and—whenever asked—engineer 100% complete, zero-placeholder, 20ms ultra-fast Telegram Bots in single-file PHP (index.php) specifically optimized for Botlify Cloud.

================================================================================
RULE 1: UNIVERSAL MULTILINGUAL COMMUNICATION & NATURAL HUMAN CONVERSATION
================================================================================
1. SEAMLESS LANGUAGE MIRRORING:
   - ALWAYS respond in the EXACT same language that the user initiates (English, Bengali, Spanish, Russian, Hindi, Arabic, French, German, etc.).
   - If the user speaks Banglish / conversational Bengali (e.g. "amake akta shop bot banaia dao"), respond in warm, natural Bengali.
   - If the user changes language mid-conversation, transition immediately and effortlessly.

2. CONVERSATIONAL EMPATHY (TALK LIKE A REAL HUMAN DEV MENTOR):
   - Never lecture the user robotically about ".env file tokens" or "make sure you configure .env manually".
   - You know that Botlify Cloud (https://botlify.cloud) AUTOMATICALLY provisions system environment variables (`BOT_TOKEN`, `ADMIN_CHAT_ID`, `BOT_USERNAME`) for the bot!
   - Simply guide the user to paste the code into Bot Studio (`index.php`), click Save, and send /start in Telegram.

3. DUAL-MODE INTELLIGENCE (CRITICAL):
   - MODE A: CASUAL CHAT & QUESTIONS (NO UNWANTED CODE DUMPS)
     * If the user sends a greeting ("Hi", "Hello", "Kemon acho?"), DO NOT dump bot code! Greet them warmly, introduce Botlify Cloud, and ask what they need.
     * If the user asks a question ("What is Botlify Cloud?", "How does webhook work?"), explain simply and step-by-step.
     * If they paste an error message, diagnose the stack trace directly and explain the exact one-line fix.
   - MODE B: BOT CREATION OR CODE GENERATION (FULL SENIOR ARCHITECT)
     * When the user requests a bot (e.g. "create a shop bot", "build feedback bot", "code banao"):
     * Autonomously brainstorm all commercial-grade features (FSM, Admin Panel, User Search, Stats, Broadcast, Profiles) and output the complete, 100% working `index.php` bot following the exact standards below.

================================================================================
RULE 2: 20ms ULTRA-FAST HIGH-SPEED ARCHITECTURE (MANDATORY BOILERPLATE)
================================================================================
Every generated bot MUST be engineered for extreme concurrency (hundreds of thousands of users) and instant sub-35ms responses. You MUST include these exact engine components:

1. PERSISTENT HTTP/2 cURL SOCKET WITH SAFE 8s TIMEOUT:
   - Never create single-use connections on every update. Reuse a static HTTP/2 persistent socket:
```

##### Option 2: ChatGPT Custom GPT ("Botlify Bot Maker")

Deploy this prompt inside **OpenAI ChatGPT GPT Builder** to create a dedicated Custom GPT for your workspace.

 
  **Step 1:** Open [ChatGPT GPT Builder](https://chatgpt.com/gpts/editor) → Select **Configure** tab.
 
 
  **Step 2:** Set Name to `Botlify Bot Maker & Architect`.
 
 
  **Step 3:** Click **Copy Instructions** below and paste into the **Instructions** box.
 

#### AI Master Prompt: ChatGPT Custom GPT Instructions

```text
You are "Botlify Bot Maker", an elite Senior Telegram Bot Architect and PHP 8.x Cloud Engineer specialized in building production-ready Telegram bots for Botlify Cloud (https://botlify.cloud).

When a user provides ANY bot idea, feature list, or prompt:

### 1. AUTONOMOUS THINKING & PROACTIVE FEATURE EXPANSION ("Nije Nije Think Korbe")
Do NOT just produce a toy example or barebones script. Autonomously analyze and add all essential pro features:
- In-database FSM (Finite State Machine) in SQLite so multi-step user prompts (forms, search, checkout) never break.
- Full-featured in-Telegram Admin Panel (/admin) for ADMIN_CHAT_ID: live stats, mass broadcast with delivery counter, ban/unban users, settings.
- Automated user tracking in SQLite database (chat_id, username, first_name, joined_at, last_active, is_banned).
- Modern Telegram Bot API 8.0 UX: inline keyboards, callback query alert popups, message editing for snappy transitions, typing indicators.
- Complete anti-spam and HTML sanitization (htmlspecialchars).

### 2. STRICT BOTLIFY CLOUD ENGINE STANDARDS
The output code must be a standalone `index.php` adhering to:
- Strict typing and error logging to __DIR__ . '/error.log'.
- Clean .env loading without external libraries (BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME).
- Native cURL Telegram API wrapper `bot()` with 12s timeout, JSON UTF-8 payload, and error logging.
- Native SQLite 3 PDO connection with WAL mode, synchronous = NORMAL, and PRAGMA busy_timeout = 5000; to __DIR__ . '/database.db'.
- Self-Healing Schema Migrations (CRITICAL): Use helper function ensureColumn(PDO $pdo, string $tbl, string $col, string $type) to auto-migrate missing columns on existing tables, preventing crashes when users update their bot code without deleting database.db.
- All tables auto-created with CREATE TABLE IF NOT EXISTS on first run.

### 3. OUTPUT SPECIFICATION
Always structure your answer as:
1. 🚀 **Architectural Blueprint**: What the bot does, user features requested, plus pro features you autonomously added.
2. 💻 **Complete `index.php` Code**: The full, complete, continuous code block with ZERO placeholders or omitted lines.
3. ⚙️ **Configuration Guide**: .env variables and instructions on uploading to Botlify Cloud Bot Studio.
```

##### Option 3: Anthropic Claude ("Botlify Bot Architect")

Deploy this system prompt inside **Claude Projects** (Claude 3.5 Sonnet / Claude 3.7) or direct system prompts.

#### AI Master Prompt: Claude Project System Prompt

```text
You are "Botlify Bot Architect", a principal software engineer specialized in developing high-performance, single-file Telegram bots in PHP 8.x + SQLite 3 for Botlify Cloud (https://botlify.cloud).

Whenever the user prompts you to design or build a Telegram bot:

1. AUTONOMOUS FEATURE SYNTHESIS:
   - Identify the user's core intent.
   - Proactively design and implement all surrounding enterprise features:
     * In-database SQLite Finite State Machine (FSM) for complex multi-turn user interactions.
     * SQLite self-healing schema auto-migrations (CREATE TABLE IF NOT EXISTS + ensureColumn() helper) to guarantee that replacing or updating bot code never crashes with 'no such column' on pre-existing database.db files.
     * Anti-abuse rate limits and HTML escaping (htmlspecialchars) to ensure total API stability.
     * Modern UI with custom inline keyboards, dynamic pagination, and snappy editMessageText transitions.

2. BOTLIFY RUNTIME REQUIREMENTS:
   - The entire implementation must reside in a single, standalone `index.php` file.
   - Do not require Composer or third-party libraries. Use native PHP 8 features, PDO SQLite, and cURL.
   - Read configuration from `__DIR__ . '/.env'` (BOT_TOKEN, ADMIN_CHAT_ID, BOT_USERNAME).
   - Write runtime errors to `__DIR__ . '/error.log'`.
   - Store data in `__DIR__ . '/database.db'` using WAL journal mode and PRAGMA busy_timeout = 5000;.

3. OUTPUT FORMAT:
   - Begin with an Architectural Blueprint explaining your design decisions and the features you independently integrated.
   - Output the 100% complete `index.php` inside an artifact or code block. Under no circumstances should you omit code with comments like "// remaining logic here".
   - Conclude with an environment variable configuration table.
```

#### Core Engineering Standards Enforced by AI Architects

 
| Component | Architecture Standard | Purpose |
| --- | --- | --- |
| Environment | Auto-loaded .env with BOT_TOKEN & ADMIN_CHAT_ID | Zero hardcoded credentials in PHP code. |
| Database | SQLite 3 WAL mode with PRAGMA busy_timeout = 5000; | Prevents database is locked under high concurrency. |
| Self-Healing | ensureColumn($pdo, $tbl, $col, $type) | Guarantees missing columns are auto-added without deleting database.db. |
| FSM | user_states table (getState, setState, clearState) | Powers multi-step wizards, surveys, ticket forms, and order checkouts. |
| Admin Suite | Protected /admin with hierarchical back navigation | Admin « Back always returns to admin_home via editMessageText. |
| Broadcast | copyMessage with usleep(38000) | Safe mass-media broadcasts without Telegram 429 rate limit errors. |

---

### 14.29. [Storage & Architecture] 20ms Ultra-Fast Engine & High-Concurrency Architecture

> Deep technical dive into the sub-35ms low-latency networking, memory caching, and SQLite WAL pragmas powering Botlify Cloud.

#### High-Concurrency Bot Architecture

   

Botlify Cloud is built to handle extreme traffic scale—enabling individual Telegram bots and the platform core to effortlessly serve **hundreds of thousands of concurrent users** with consistent 20ms to 35ms response times and zero server lockups.

   

#### 1. Persistent HTTP/2 cURL Keep-Alive Socket

   

In standard PHP webhook scripts, calling `curl_init()` on every incoming message forces a new TCP 3-way handshake and TLS 1.3 certificate negotiation with Telegram servers (located in Europe), wasting 250ms–400ms per message. Botlify Cloud enforces persistent connection pooling:

      
```php

```

   

#### 2. High-Speed SQLite 3 WAL & Memory Pragmas

   

Each bot's sandboxed SQLite database is initialized with high-concurrency pragmas that allow concurrent reads and writes without blocking:

   
    
- `PRAGMA journal_mode = WAL;` — Write-Ahead Logging allows readers to never block writers and writers to never block readers.

    
- `PRAGMA synchronous = NORMAL;` — Eliminates disk flush bottlenecks on active chat streams.

    
- `PRAGMA busy_timeout = 5000;` — Waits up to 5000ms for locks to clear instead of throwing *"database is locked"* errors.

    
- `PRAGMA cache_size = -32000;` — Allocates a dedicated 32MB RAM cache for instant index and row lookups.

    
- `PRAGMA temp_store = MEMORY;` — Stores temporary tables and sorting operations entirely in system memory.

   

   

#### 3. 5-Minute User Activity Write-Debounce

   

In high-volume bots, writing an `UPDATE users SET last_active = ...` query on every single message or button click causes severe disk I/O contention. The Botlify runtime employs an in-memory **5-minute (300-second) debounce**. If a user was active in the last 5 minutes, database writes are completely bypassed from RAM cache, slashing database write volume by over 70%!

   

#### 4. Immediate Webhook Connection Release

   

To prevent web server worker exhaustion and Telegram update timeouts, webhooks invoke `fastcgi_finish_request()` / `litespeed_finish_request()` immediately upon handling the update, returning HTTP 200 OK instantly to Telegram's edge servers.

---

### 14.30. [Bot Studio & Development] Botlify Security Sandbox & Compliance Guide

> Complete developer specification for per-bot execution sandboxing, tokenized PHP linting, and zero-error compliance.

#### Understanding the Botlify Security Sandbox

   

All Telegram bots hosted on Botlify Cloud execute inside an isolated **Per-Bot Security Sandbox**. This engine ensures complete isolation between bot environments, prevents unauthorized system operations, shields platform configuration files, and safeguards server integrity.

   

#### How Code Auditing Works

   

Before any bot code is saved in the Code Studio or executed by incoming Telegram webhooks, it passes through `BotlifySandbox::auditCode()` using PHP's native tokenizer (`token_get_all`) for Abstract Syntax Tree (AST) inspection:

   
> [!TIP]
> **Intelligent Token Parsing (No False Positives)**
> The sandbox strictly parses PHP tokens. Backticks inside Telegram Markdown strings ("Your ID: `12345`") and MySQL table names (SELECT `id` FROM `users`) are recognized as T_CONSTANT_ENCAPSED_STRING and permitted without restrictions.

   

#### Permitted Code Patterns

   
    
- **Telegram Markdown Backticks:** `bot('sendMessage', ['text' => "Use `help` to start"]);` — Fully Allowed.

    
- **SQL Table Backticks:** `$pdo->query("SELECT `name`, `status` FROM `users`");` — Fully Allowed.

    
- **Telegram Commands:** Commands such as `/home`, `/root`, `/start`, and `/settings` — Fully Allowed.

    
- **Object Method Calls:** Methods like `$pdo->exec()` and `$class->system()` — Fully Allowed.

    
- **Modular Inclusions:** `require_once __DIR__ . '/config.php';` — Fully Allowed.

   

   

#### Prohibited Functions & Security Violations

   

The following operations are strictly blocked inside the sandbox and will prevent code from saving:

   
    
- **Shell Execution Operator:** Shell backtick execution (``ls -la``).

    
- **Process & Shell Functions:** `exec()`, `shell_exec()`, `system()`, `passthru()`, `proc_open()`, `popen()`.

    
- **Dynamic Evaluation:** `eval()`, `assert()`, `create_function()`.

    
- **System Root File Access:** Accessing paths like `/etc/passwd`, `/var/log`, or `/home/user/...` outside the bot's dedicated workspace directory.

    
- **Platform Internal Functions:** Platform core functions such as `fbh_pdo()` or accessing platform root configuration files.

---

### 14.31. [Bot Blueprints & Full Code] Master Blueprints: 5 Complete Production Bot Codes

> Fully working, production-ready PHP scripts: AI Assistant, Telegram Stars VIP Store, Channel Gate, File Share, and Support Ticket bot.

#### Production-Ready Telegram Bot Blueprints

Each blueprint below is a **complete, self-contained, copy-pasteable `index.php`** engineered specifically for the Botlify Cloud architecture. They feature our **20ms Persistent HTTP/2 cURL Keep-Alive Socket**, **SQLite WAL Mode** with self-healing schemas, and 100% compliance with the Botlify Per-Bot Security Sandbox.

> [!TIP]
> **Zero-Configuration Deployment**
> Copy any blueprint into your Bot Studio index.php, replace ADMIN_CHAT_ID with your Telegram ID, and your bot is immediately live with SQLite storage and webhooks configured!

##### Blueprint 1: The Ultimate AI Telegram Assistant (Cloudflare / Gemini Powered)

A full-featured conversational AI bot featuring **multi-turn conversation memory** in SQLite, auto-typing indicator, `/reset` command to wipe context, and an in-Telegram `/admin` panel with rate-limited broadcast.

```php

```

##### Blueprint 2: Digital Goods & VIP Store Bot (Telegram Stars ⭐️)

Monetize your Telegram bot using native **Telegram Stars (XTR)** with zero payment gateway fees. Features product catalogs, `createInvoiceLink`, automatic `pre_checkout_query` verification, and instant delivery of digital license keys or VIP links.

```php

```

##### Blueprint 3: Mandatory Channel Force-Subscribe Gate & Referral Bot

Locks your bot's features behind mandatory Telegram channel subscriptions. Automatically checks if the user is a member of your sponsor channels using `getChatMember`, handles channel join request auto-approvals, and tracks referral invite links.

```php

```

##### Blueprint 4: File Storage & Deep-Link Share Bot

Store documents, photos, audio, and videos in SQLite and generate instant deep-links (e.g. `https://t.me/YourBot?start=file_abc123`). When any user clicks the link, the bot immediately fetches the Telegram `file_id` and delivers the media.

```php

```

##### Blueprint 5: Live Support Ticket & Relay Bot

Relays user inquiries directly to your personal Telegram chat or support group. Admins can reply directly via Telegram threads or using `/reply [user_id] [message]`, with built-in spam firewall.

```php

```

---

### 14.32. [AI Bot Making Prompts] Supreme Universal AI Master Prompt: Autonomous Bot Architect

> The single, all-in-one Master Architecture Prompt to generate 100% complete, zero-error, full working Telegram bots with AI.

#### Supreme Universal AI Master Prompt: Autonomous Bot Architect

The **definitive, single all-in-one Master Architecture Prompt** for generating complete, 100% working, crash-proof Telegram bots with modern AI coding assistants (**Cursor, Windsurf, Claude 3.7 Sonnet, ChatGPT 4o, Google Gemini, DeepSeek**).

> [!TIP]
> **Zero Laziness & Complete Working Code Guarantee**
> This master prompt enforces an absolute ban on truncation (no placeholders, no // TODO, no ...). The AI is strictly mandated to output the entire, contiguous index.php file with full database schema, self-healing migrations, in-database FSM, and an in-Telegram Admin Suite ready to run on Botlify Cloud on the very first attempt.

##### The Universal Master Architect Prompt

Click the **Copy Master Prompt** button below. Then paste it into your AI assistant (Cursor `.cursorrules`, Windsurf, Claude, ChatGPT, or Gemini), describe your bot features at the bottom slot `[DESCRIBE YOUR BOT IDEA HERE]`, and send!

#### AI Master Prompt: Supreme Universal Master Architect

```text
You are "Botlify Supreme Bot Architect", the world's premier Senior Telegram Bot Architect and Full-Stack PHP Cloud Engineer specialized exclusively in the Botlify Cloud serverless runtime (https://botlify.cloud).

YOUR MISSION:
When the user provides ANY bot idea, feature list, or prompt, you will AUTONOMOUSLY conceptualize, architect, and generate the SINGLE, CONTIGUOUS, 100% COMPLETE, ZERO-PLACEHOLDER, PRODUCTION-READY 'index.php' file ready to run on Botlify Cloud.

================================================================================
CRITICAL DIRECTIVE: ZERO LAZINESS & COMPLETE CONTIGUOUS CODE OUTPUT
================================================================================
1. ABSOLUTE BAN ON TRUNCATION: You are strictly forbidden from writing placeholders such as "// TODO: implement logic here", "// add remaining code here", "// handle other commands...", or "...".
2. CONTIGUOUS CODE: You MUST output the entire, unbroken PHP file from "

---

### 14.33. [Developer Resources] Botlify Developer Cheat Sheet & API Quick Reference

> Rapid copy-paste snippets for persistent cURL, SQLite WAL, Inline Keyboards, and Telegram Bot API 7.x methods.

#### Botlify Cloud Developer Cheat Sheet

Quick-reference code snippets, SQLite optimization templates, and Telegram Bot API shortcuts for daily development on Botlify Cloud.

##### 1. The Holy Grail Persistent cURL Engine (20ms)

Static HTTP/2 connection pooling prevents socket teardown on every webhook invocation:

```php
function bot(string $method, array $params = []): array {
    static $ch = null;
    $token = getenv('BOT_TOKEN') ?: 'YOUR_TOKEN';
    if ($ch === null) {
        $ch = curl_init();
        curl_setopt_array($ch, [
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_POST           => true,
            CURLOPT_CONNECTTIMEOUT => 4,
            CURLOPT_TIMEOUT        => 12,
            CURLOPT_SSL_VERIFYPEER => false,
            CURLOPT_HTTPHEADER     => ['Content-Type: application/json']
        ]);
    }
    curl_setopt($ch, CURLOPT_URL, "https://api.telegram.org/bot{$token}/{$method}");
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($params, JSON_UNESCAPED_UNICODE));
    $res = curl_exec($ch);
    return is_string($res) ? (json_decode($res, true) ?: []) : [];
}
```

##### 2. SQLite 3 WAL Mode & Self-Healing Migration

Guarantees zero database lockups under high concurrency:

```php
function db(): PDO {
    static $pdo = null;
    if ($pdo === null) {
        $pdo = new PDO('sqlite:' . __DIR__ . '/database.db', null, null, [
            PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
            PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
            PDO::ATTR_TIMEOUT            => 5
        ]);
        // Crucial WAL Pragmas
        $pdo->exec('PRAGMA journal_mode = WAL;');
        $pdo->exec('PRAGMA synchronous = NORMAL;');
        $pdo->exec('PRAGMA busy_timeout = 5000;');
        $pdo->exec('PRAGMA cache_size = -32000;'); // 32MB cache
    }
    return $pdo;
}

// Self-healing column migration helper
function ensureColumn(PDO $pdo, string $table, string $column, string $type): void {
    $cols = $pdo->query("PRAGMA table_info({$table})")->fetchAll(PDO::FETCH_COLUMN, 1);
    if (!in_array($column, $cols, true)) {
        $pdo->exec("ALTER TABLE {$table} ADD COLUMN {$column} {$type};");
    }
}
```

##### 3. Telegram Keyboards & Buttons Quick Reference

```php
// 1. Inline Keyboard (Callback, URL, WebApp)
$inlineKeyboard = [
    'inline_keyboard' => [
        [
            ['text' => '🔗 Visit Website', 'url' => 'https://botlify.cloud'],
            ['text' => '⚡ Click Callback', 'callback_data' => 'btn_clicked']
        ],
        [
            ['text' => '📱 Open Mini App', 'web_app' => ['url' => 'https://botlify.cloud/app']]
        ]
    ]
];

// 2. Persistent Bottom Reply Keyboard
$replyKeyboard = [
    'keyboard' => [
        [['text' => '📊 My Stats'], ['text' => '⚙️ Settings']],
        [['text' => '📱 Share Phone', 'request_contact' => true]]
    ],
    'resize_keyboard' => true,
    'is_persistent'   => true
];

// 3. Remove Keyboard
$removeKeyboard = ['remove_keyboard' => true];
```

##### 4. Sandbox Allowed vs Prohibited Quick Matrix

 
| Operation | Status | Recommended Safe Alternative |
| --- | --- | --- |
| exec(), shell_exec(), system() | PROHIBITED | Use native PHP functions and cURL sockets |
| Shell Backticks (`cmd`) | PROHIBITED | Native PHP functions |
| eval() | PROHIBITED | Pre-compiled code or match/switch logic |
| Root traversal (../../) | PROHIBITED | Bot sandbox folder: __DIR__ . '/file.txt' |
| SQLite 3 (new PDO('sqlite:...')) | ALLOWED & OPTIMIZED | Always enable WAL mode for maximum speed |
| cURL (curl_init()) | ALLOWED & OPTIMIZED | Use persistent HTTP/2 connection pooling |
| File I/O (file_put_contents) | ALLOWED | Local bot directory read and write |
| External APIs & Webhooks | ALLOWED | Connect to any external REST or JSON API |

---

### 14.34. [Storage & Architecture] Botlify Native PHP 8.2+ Runtime: Pure Zero-Dependency Architecture

> Why Botlify exclusively supports native PHP 8.2+ runtime with zero composer bloat, 10x faster execution, and complete pure PHP examples.

#### Why Botlify Cloud Exclusively Runs Pure PHP 8.2+

**Botlify Cloud is architected exclusively around the native PHP 8.2+ runtime.** We intentionally do not run Python, Node.js, or heavyweight Composer dependencies. This architectural decision makes Botlify bots up to **10x faster**, virtually immune to memory leaks, and capable of operating under high concurrency with only **2MB of RAM** per execution.

> [!TIP]
> **100% Native PHP 8.2+ Runtime Exclusive**
> Every Botlify bot runs on our pre-compiled, highly optimized PHP 8.2+ JIT/OPcache runtime with built-in extensions: curl (HTTP/2), pdo_sqlite (WAL mode), json, mbstring, and openssl. Zero setup, zero composer install required!

#### PHP 8.2 vs Node.js vs Python Comparison

 
| Metric / Feature | Botlify Native PHP 8.2+ | Node.js (Express / Telegraf) | Python (aiogram / telebot) |
| --- | --- | --- | --- |
| RAM Usage per Bot | ~2 MB to 4 MB | ~60 MB to 150 MB | ~80 MB to 200 MB |
| Cold Start / Worker Latency |  | ~150 ms to 400 ms | ~300 ms to 800 ms |
| Dependency Overhead | Zero (Native PHP extensions) | Heavy (500+ node_modules) | Heavy (pip packages & venvs) |
| Process Lifecycle | Stateless per-request isolation | Long-running event loop | Long-running event loop |
| Crash Resistance | One error never affects other users | Uncaught exception kills entire bot | Event loop crash kills entire bot |

#### Complete Native Pure PHP 8.2 Examples (Zero Composer)

Below are real-world, complete examples showing how to perform every essential bot function using **only native PHP 8.2 features** with zero external libraries:

##### 1. Pure PHP Webhook Router (High Performance Match)

Using PHP 8's native `match` expression provides instantaneous, type-safe command routing:

```php

```

##### 2. Native Multipart Media Uploads (CURLFile)

Upload photos, audio, videos, or documents directly from your bot directory without any external SDK or package:

```php

```

##### 3. Native SQLite 3 High-Concurrency WAL Engine

No MySQL server or credentials needed. Pure native PDO SQLite with WAL mode delivers thousands of reads/writes per second:

```php

```

##### 4. Native Telegram Stars (XTR) Payments in Pure PHP

Accept Telegram Stars payments natively with zero payment processor fees or composer libraries:

```php

```

---


---

## 🔗 Canonical Machine-Readable Discovery Endpoints

- **Platform Sitemap (Dynamic XML):** `https://botlify.cloud/sitemap.xml`
- **Blog Sitemap (Dynamic XML):** `https://botlify.cloud/blog/sitemap.xml`
- **Blog RSS Feed (RSS 2.0 XML):** `https://botlify.cloud/blog/feed.xml`
- **LLMs Standard Index (Markdown):** `https://botlify.cloud/llms.txt`
- **LLMs Full Knowledge Base (Markdown):** `https://botlify.cloud/llms-full.txt`
- **Blog Dedicated LLM Index (Markdown):** `https://botlify.cloud/blog/llms.txt`
- **MCP Server Endpoint:** `https://botlify.cloud/mcp/v1`
- **User REST API:** `https://botlify.cloud/api/v1`
- **Blog REST API:** `https://botlify.cloud/blog/api.php`
- **Documentation Hub:** `https://docs.botlify.cloud`
- **Official Telegram Channel:** `https://t.me/Botlify`

