Updates, Callbacks and Persistent State

Raw MD
Event routing, callback acknowledgement, formatting, SQLite and files.

Treat updates as different event types

A Telegram update is not always a text message. It can carry a callback query, channel post, edited message, business event, inline query or another supported event. Check the field before dereferencing it. Configure allowed updates for the event types your bot needs; loading helpers does not change webhook subscriptions.

Code example
<?php
declare(strict_types=1);
$update = json_decode((string) file_get_contents('php://input'), true) ?: [];
if (isset($update['callback_query'])) {
    // Route to your callback handler.
} elseif (isset($update['message']['text'])) {
    // Route to your text/command handler.
} elseif (isset($update['message']['document'])) {
    // Route to your document handler.
} elseif (isset($update['channel_post'])) {
    // Route to your channel handler.
}

Callback data is an action identifier, not proof that a user has permission. Check the sender before administration actions. Some callback queries refer to inline messages rather than an ordinary message; do not assume a chat/message ID is always present.

Acknowledge callbacks promptly

Code example
<?php
declare(strict_types=1);
tg_all_fun();
$update = json_decode((string) file_get_contents('php://input'), true) ?: [];
$callback = $update['callback_query'] ?? null;
if ($callback !== null) {
    tg_answer_cb($callback['id']);
    $action = $callback['data'] ?? '';
    if ($action === 'demo_info' && isset($callback['message']['chat']['id'], $callback['message']['message_id'])) {
        tg_edit($callback['message']['chat']['id'], $callback['message']['message_id'], 'Demo information');
    }
}

For privileged actions, validate the sender and the requested resource on every update. Do not authorize a user merely because they know a callback string. Use the generated API wrapper if you need parameters not present in a convenience signature.

Message text, HTML and entities

tg_send defaults to HTML formatting. Escape user-controlled text before embedding it in HTML, or request plain text with ['parse_mode' => null]. The exact API wrappers do not add the shorthand's HTML defaults. Entity offsets/lengths use UTF-16 units; string byte positions are not interchangeable with entity offsets.

Code example
<?php
declare(strict_types=1);
tg_all_fun();
$update = json_decode((string) file_get_contents('php://input'), true) ?: [];
$message = $update['message'] ?? [];
if (isset($message['chat']['id'], $message['text'])) {
    tg_send($message['chat']['id'], $message['text'], ['parse_mode' => null]);
}

SQLite state across requests

Local variables disappear after the request. Store conversation state in your bot's database. Use __DIR__ to anchor the path and prepared statements for user values. The following schema is a starting point, not a complete conversation workflow.

Code example
<?php
declare(strict_types=1);
$db = new PDO('sqlite:' . __DIR__ . '/database.db', null, null, [
    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
]);
$db->exec('PRAGMA busy_timeout = 3000');
$db->exec('CREATE TABLE IF NOT EXISTS conversation_state (
    chat_id TEXT PRIMARY KEY,
    step TEXT NOT NULL,
    updated_at INTEGER NOT NULL
)');
// Once $chatId and $nextStep are validated by your application:
// $statement = $db->prepare('INSERT INTO conversation_state VALUES (?, ?, ?)
//     ON CONFLICT(chat_id) DO UPDATE SET step=excluded.step, updated_at=excluded.updated_at');
// $statement->execute([(string)$chatId, $nextStep, time()]);

Keep transactions short. Do not hold a database write transaction open while waiting for Telegram. WAL mode can improve concurrency when supported, but is not a replacement for bounded writes and appropriate filesystem support.

Duplicate updates and side effects

Track Telegram update_id if duplicate processing matters. A unique key can prevent duplicate local inserts. It does not guarantee exactly-once remote actions: a process can fail after Telegram accepts a request but before the local database records completion. Payments, inventory and other important actions need durable states, reconciliation and operation-specific retry rules.

A webhook HTTP 200 response acknowledges delivery; it does not prove every application action succeeded. Botlify may acknowledge handled failures to avoid repeated delivery loops. Review application state and error.log, not only the HTTP status.

Files and media

Store file_id with the bot identity and media type; it is not portable across bots. file_unique_id identifies a file but cannot download/resend it. getFile returns a Telegram path, not a path on the Botlify server. tg_download_file returns local_path, file_name, direct_tg_url and url; check the local path before using it. The URL fields can contain credentials, so keep them server-side.

See file, custom emoji, effects and album examples. Refer to Telegram's Bot API for method limits, permitted formats and event fields.