Complete Bot Examples: Helpers and Plain PHP
Before copying
Use one example as the test bot’s index.php, not both in the same file. Configure the bot token and administrator through the platform. The examples respond to /start, /help, ordinary text and callback buttons. They deliberately use plain message text for user input. They are starting points, not a complete production queue, deduplication or payment system.
Example A: Botlify helpers
Requires the deployed opt-in Botlify runtime. The exact loader spelling is tg_all_fun();, with both underscores. It comes after strict_types and before helper calls.
<?php
declare(strict_types=1);
tg_all_fun();
$update = json_decode((string)file_get_contents('php://input'), true) ?: [];
if (!is_array($update)) $update = [];
if (isset($update['callback_query'])) {
$query = $update['callback_query'];
tg_answer_cb((string)$query['id'], 'Button received');
http_response_code(200);
return;
}
$message = $update['message'] ?? null;
if (!is_array($message) || !isset($message['text'])) {
http_response_code(200);
return;
}
$chatId = $message['chat']['id'];
$text = trim($message['text']);
$command = explode('@', explode(' ', $text)[0])[0];
$reply = match ($command) {
'/start' => 'Hello! This bot uses Botlify helpers.',
'/help' => 'Send text or press the test button.',
default => 'You wrote: ' . $text,
};
$result = tg_send($chatId, $reply, [
'parse_mode' => null,
'reply_markup' => tg_inline([[tg_btn('Test button', 'demo:test', ['style'=>'primary'])]]),
]);
if (!($result['ok'] ?? false)) {
error_log('[Example] Telegram send failed; error_code=' . ($result['error_code'] ?? 'unknown'));
}
http_response_code(200);
Example B: plain PHP/cURL
This example never calls tg_all_fun or a tg_* helper. In Botlify, the environment supplies BOT_TOKEN. Outside Botlify, supply it yourself and configure the webhook. PHP cURL and a working CA trust store are needed for the verified HTTPS connection.
<?php
declare(strict_types=1);
// Botlify exports BOT_TOKEN. Standalone PHP must supply its own environment.
$token = (string)(getenv('BOT_TOKEN') ?: '');
if ($token === '' || !function_exists('curl_init')) {
error_log('[Example] Missing BOT_TOKEN or cURL.');
http_response_code(500);
return;
}
function demoTelegram(string $token, string $method, array $params): array
{
$handle = curl_init('https://api.telegram.org/bot' . $token . '/' . $method);
curl_setopt_array($handle, [
CURLOPT_POST => true,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_CONNECTTIMEOUT => 5,
CURLOPT_TIMEOUT => 15,
CURLOPT_SSL_VERIFYPEER => true,
CURLOPT_SSL_VERIFYHOST => 2,
CURLOPT_HTTPHEADER => ['Content-Type: application/json'],
CURLOPT_POSTFIELDS => json_encode($params, JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR),
]);
$raw = curl_exec($handle);
curl_close($handle);
if (!is_string($raw)) return ['ok'=>false, 'description'=>'Transport failure'];
$response = json_decode($raw, true);
return is_array($response) ? $response : ['ok'=>false, 'description'=>'Invalid JSON response'];
}
$update = json_decode((string)file_get_contents('php://input'), true) ?: [];
if (!is_array($update)) $update = [];
if (isset($update['callback_query'])) {
demoTelegram($token, 'answerCallbackQuery', [
'callback_query_id'=>(string)$update['callback_query']['id'],
'text'=>'Button received',
'show_alert'=>false,
]);
http_response_code(200);
return;
}
$message = $update['message'] ?? null;
if (!is_array($message) || !isset($message['text'])) {
http_response_code(200);
return;
}
$text = trim($message['text']);
$command = explode('@', explode(' ', $text)[0])[0];
$reply = match ($command) {
'/start' => 'Hello! This bot uses plain PHP/cURL.',
'/help' => 'Send text or press the test button.',
default => 'You wrote: ' . $text,
};
$result = demoTelegram($token, 'sendMessage', [
'chat_id'=>$message['chat']['id'],
'text'=>$reply,
'reply_markup'=>['inline_keyboard'=>[[
['text'=>'Test button', 'callback_data'=>'demo:test', 'style'=>'primary'],
]]],
]);
if (!($result['ok'] ?? false)) {
error_log('[Example] Telegram send failed; error_code=' . ($result['error_code'] ?? 'unknown'));
}
http_response_code(200);
How to verify both
Test one version at a time. Send /start, /help, ordinary text containing < and >, and press the button. Confirm one reply per text message and a callback acknowledgement. An API success response verifies acceptance; inspect the client to check actual button/message rendering. Switch examples only after backing up your code.
Move toward production
Keep replies within Telegram text limits; split long content deliberately. Add per-user state, permissions for administrative actions, operation-level deduplication, bounded retries and structured diagnostics. Do not register a webhook on every update or keep a long polling loop inside the hosted webhook. Use persistent state and testing guidance.