Skip to content

Examples

maule edited this page Aug 16, 2026 · 1 revision

Examples

Real-world code examples for common bot use cases.

Basic Echo Bot

Echoes back user messages.

<?php
declare(strict_types=1);

use TGbotPHP\botTG;

require_once "botlib.php";

$token = getenv('TELEGRAM_BOT_TOKEN');
$updates = file_get_contents("php://input");
$bot = new botTG(token: $token, updates: $updates);

if ($bot->isPrivate()) {
    $message = $bot->getTextMessage();
    if ($message) {
        $bot->sendMessage(
            chatId: $bot->getChatId(),
            text: "You said: $message"
        );
    }
}

http_response_code(200);

Command Handler

Handle multiple commands.

<?php
require_once "botlib.php";

$token = getenv('TELEGRAM_BOT_TOKEN');
$updates = file_get_contents("php://input");
$bot = new botTG(token: $token, updates: $updates);

// Define commands
$commands = [
    '/start' => 'Start using the bot',
    '/help' => 'Show help message',
    '/settings' => 'Open settings',
];

// Handle /start
$bot->commandSimple("/start", [
    "text" => "Welcome! Use /help for commands.",
    "keyboard" => $bot->buildKeyboardOfInline([
        "Help" => "help",
        "Settings" => "settings",
    ]),
]);

// Handle /help
$bot->commandSimple("/help", [
    "text" => "Available commands:\n" . 
              implode("\n", array_map(
                  fn($cmd, $desc) => "$cmd - $desc",
                  array_keys($commands),
                  array_values($commands)
              )),
]);

// Handle /settings
$bot->commandSimple("/settings", [
    "text" => "Settings",
    "keyboard" => $bot->buildKeyboardOfInline([
        "Language" => "lang",
        "Notifications" => "notify",
        "← Back" => "back",
    ]),
]);

http_response_code(200);

Interactive Menu

Navigation between menus.

<?php
require_once "botlib.php";

$token = getenv('TELEGRAM_BOT_TOKEN');
$updates = file_get_contents("php://input");
$bot = new botTG(token: $token, updates: $updates);

// Menus
$mainMenu = $bot->buildKeyboardOfInline([
    "Profile" => "profile",
    "Browse" => "browse",
    "Settings" => "settings",
]);

$profileMenu = $bot->buildKeyboardOfInline([
    "View Stats" => "stats",
    "Edit Info" => "edit",
    "← Back" => "back",
]);

$settingsMenu = $bot->buildKeyboardOfInline([
    "Language" => "lang",
    "Theme" => "theme",
    "Notifications" => "notify",
    "← Back" => "back",
]);

// Start command
$bot->commandSimple("/start", [
    "text" => "Main Menu",
    "keyboard" => $mainMenu,
]);

// Profile
$bot->simpleCallbackResponse("profile", [
    "text" => "👤 Profile\n\nUser ID: 123456",
    "keyboard" => $profileMenu,
]);

// Browse
$bot->simpleCallbackResponse("browse", [
    "text" => "📚 Browse Content",
    "keyboard" => $bot->buildKeyboardOfInline([
        "Category 1" => "cat1",
        "Category 2" => "cat2",
        "← Back" => "back",
    ]),
]);

// Settings
$bot->simpleCallbackResponse("settings", [
    "text" => "⚙️ Settings",
    "keyboard" => $settingsMenu,
]);

// Back to main
$bot->simpleCallbackResponse("back", [
    "text" => "Main Menu",
    "keyboard" => $mainMenu,
]);

http_response_code(200);

Quiz Bot

Interactive quiz with scoring.

<?php
require_once "botlib.php";

$token = getenv('TELEGRAM_BOT_TOKEN');
$updates = file_get_contents("php://input");
$bot = new botTG(token: $token, updates: $updates);

// Quiz questions
$questions = [
    'q1' => [
        'text' => 'What is 2 + 2?',
        'correct' => 'q1_correct',
        'wrong' => 'q1_wrong',
    ],
    'q2' => [
        'text' => 'What is the capital of France?',
        'correct' => 'q2_correct',
        'wrong' => 'q2_wrong',
    ],
];

// Start quiz
$bot->commandSimple("/quiz", [
    "text" => "Let's start a quiz! Question 1:",
    "keyboard" => $bot->buildKeyboardOfInline([
        "Begin" => "quiz_start",
    ]),
]);

// Question 1
$bot->simpleCallbackResponse("quiz_start", [
    "text" => $questions['q1']['text'],
    "keyboard" => $bot->buildKeyboardOfInline([
        "4" => "q1_correct",
        "5" => "q1_wrong",
    ]),
]);

// Correct answer
$bot->simpleCallbackResponse("q1_correct", [
    "text" => "✅ Correct! You got 1 point.",
    "keyboard" => $bot->buildKeyboardOfInline([
        "Next Question" => "quiz_q2",
    ]),
]);

// Wrong answer
$bot->simpleCallbackResponse("q1_wrong", [
    "text" => "❌ Wrong! The answer is 4.",
    "keyboard" => $bot->buildKeyboardOfInline([
        "Next Question" => "quiz_q2",
    ]),
]);

// Question 2
$bot->simpleCallbackResponse("quiz_q2", [
    "text" => $questions['q2']['text'],
    "keyboard" => $bot->buildKeyboardOfInline([
        "Paris" => "q2_correct",
        "London" => "q2_wrong",
    ]),
]);

// Final score
$bot->simpleCallbackResponse("q2_correct", [
    "text" => "✅ Correct! Final score: 2/2 🏆",
]);

http_response_code(200);

Photo Gallery

Browse photos with pagination.

<?php
require_once "botlib.php";

$token = getenv('TELEGRAM_BOT_TOKEN');
$updates = file_get_contents("php://input");
$bot = new botTG(token: $token, updates: $updates);

class PhotoGallery {
    private array $photos = [
        ['name' => 'photo1.jpg', 'title' => 'Sunset'],
        ['name' => 'photo2.jpg', 'title' => 'Mountain'],
        ['name' => 'photo3.jpg', 'title' => 'Ocean'],
    ];
    
    public function showPhoto($bot, $chatId, $index = 0): void {
        $photo = $this->photos[$index] ?? $this->photos[0];
        $isFirst = $index === 0;
        $isLast = $index === count($this->photos) - 1;
        
        $buttons = [];
        if (!$isFirst) {
            $buttons["← Prev"] = "photo_" . ($index - 1);
        }
        $buttons["Info"] = "photo_info_$index";
        if (!$isLast) {
            $buttons["Next →"] = "photo_" . ($index + 1);
        }
        
        $bot->sendMessage(
            chatId: $chatId,
            text: $photo['title'],
            photo: $photo['name'],
            keyboard: $bot->buildKeyboardOfInline($buttons)
        );
    }
}

$gallery = new PhotoGallery();

$bot->commandSimple("/gallery", [
    "text" => "📸 Photo Gallery",
    "keyboard" => $bot->buildKeyboardOfInline([
        "View Gallery" => "photo_0",
    ]),
]);

$bot->simpleCallbackResponse("photo_0", null);
// (Handle with custom logic)

http_response_code(200);

Reminder Bot

Store and send reminders.

<?php
require_once "botlib.php";

$token = getenv('TELEGRAM_BOT_TOKEN');
$updates = file_get_contents("php://input");
$bot = new botTG(token: $token, updates: $updates);

class ReminderBot {
    private string $remindersFile;
    
    public function __construct() {
        $this->remindersFile = __DIR__ . '/reminders.json';
        if (!file_exists($this->remindersFile)) {
            file_put_contents($this->remindersFile, '{}');
        }
    }
    
    public function addReminder($userId, $text): void {
        $reminders = json_decode(
            file_get_contents($this->remindersFile),
            true
        );
        
        if (!isset($reminders[$userId])) {
            $reminders[$userId] = [];
        }
        
        $reminders[$userId][] = [
            'text' => $text,
            'date' => date('Y-m-d H:i:s'),
        ];
        
        file_put_contents(
            $this->remindersFile,
            json_encode($reminders, JSON_PRETTY_PRINT)
        );
    }
    
    public function getReminders($userId): array {
        $reminders = json_decode(
            file_get_contents($this->remindersFile),
            true
        );
        
        return $reminders[$userId] ?? [];
    }
}

$reminder = new ReminderBot();

$bot->commandSimple("/remind", [
    "text" => "📝 Remind me\n\nReply with what to remind you about",
    "keyboard" => $bot->buildKeyboardOfInline([
        "View Reminders" => "list_reminders",
    ]),
]);

// Handle reminder text
if ($bot->getTextMessage() && $bot->getChatId()) {
    $reminders = $reminder->getReminders($bot->getChatId());
    if (count($reminders) < 10) {
        $reminder->addReminder($bot->getChatId(), $bot->getTextMessage());
        $bot->sendMessage($bot->getChatId(), "✅ Reminder saved!");
    }
}

$bot->simpleCallbackResponse("list_reminders", [
    "text" => "Your reminders:\n" . 
              implode("\n", array_map(
                  fn($r) => "" . $r['text'],
                  $reminder->getReminders($bot->getChatId())
              )),
]);

http_response_code(200);

Counter Bot

Keep track of counts.

<?php
require_once "botlib.php";

$token = getenv('TELEGRAM_BOT_TOKEN');
$updates = file_get_contents("php://input");
$bot = new botTG(token: $token, updates: $updates);

class Counter {
    private string $file;
    
    public function __construct() {
        $this->file = __DIR__ . '/counter.json';
    }
    
    public function get($id): int {
        $data = json_decode(file_get_contents($this->file), true) ?? [];
        return $data[$id] ?? 0;
    }
    
    public function increment($id): int {
        $data = json_decode(file_get_contents($this->file), true) ?? [];
        $data[$id] = ($data[$id] ?? 0) + 1;
        file_put_contents($this->file, json_encode($data));
        return $data[$id];
    }
    
    public function reset($id): void {
        $data = json_decode(file_get_contents($this->file), true) ?? [];
        unset($data[$id]);
        file_put_contents($this->file, json_encode($data));
    }
}

$counter = new Counter();
$chatId = $bot->getChatId();

$bot->commandSimple("/counter", [
    "text" => sprintf("Counter: %d", $counter->get($chatId)),
    "keyboard" => $bot->buildKeyboardOfInline([
        "➕ +1" => "count_plus",
        "Reset" => "count_reset",
    ]),
]);

$bot->simpleCallbackResponse("count_plus", function() use ($bot, $counter, $chatId) {
    $count = $counter->increment($chatId);
    return [
        "text" => "Counter: $count",
        "keyboard" => $bot->buildKeyboardOfInline([
            "➕ +1" => "count_plus",
            "Reset" => "count_reset",
        ]),
    ];
}, edit: true);

$bot->simpleCallbackResponse("count_reset", [
    "text" => "Counter reset to 0",
]);

http_response_code(200);

See also: API Reference, Keyboards and Callbacks

Clone this wiki locally