Skip to content
Communicationv1.0.apiphptelegram

PHP Telegram Bot API

    PHP Telegram Bot API A complete PHP library for building Telegram bots. Send messages, files, manage chats, handle webhooks, and…

 

 

PHP Telegram Bot API

A complete PHP library for building Telegram bots. Send messages, files, manage chats, handle webhooks, and more.

🚀 Installation

composer require telegram/api

Or use directly without Composer:

require_once __DIR__ . '/src/Bot.php';
require_once __DIR__ . '/src/Keyboard.php';
require_once __DIR__ . '/src/Update.php';

📱 Quick Start

<?php
use Telegram\Bot;

$bot = new Bot('YOUR_BOT_TOKEN');

// Send a message
$bot->sendMessage(123456789, 'Hello World!');

// Get bot info
$me = $bot->getMe();

💬 Sending Messages

// Simple message
$bot->sendMessage($chatId, 'Hello!');

// With options (Markdown, keyboard, etc.)
$bot->sendMessage($chatId, '*Bold* and _italic_', [
    'parse_mode' => 'Markdown'
]);

// Reply to message
$bot->sendMessage($chatId, 'Reply', [
    'reply_to_message_id' => $messageId
]);

🖼️ Sending Files & Media

// Photo (local file or URL - auto-detected)
$bot->sendPhoto($chatId, '/path/to/photo.jpg');
$bot->sendPhoto($chatId, 'https://example.com/photo.jpg', 'Caption');

// Document
$bot->sendDocument($chatId, '/path/to/file.pdf', 'Document caption');

// Video
$bot->sendVideo($chatId, '/path/to/video.mp4');

// Audio
$bot->sendAudio($chatId, '/path/to/audio.mp3');

// Voice message
$bot->sendVoice($chatId, '/path/to/voice.ogg');

// Sticker
$bot->sendSticker($chatId, '/path/to/sticker.webp');

// Animation (GIF)
$bot->sendAnimation($chatId, '/path/to/animation.gif');

⌨️ Inline Keyboards

use Telegram\Keyboard;

// Create inline keyboard
$keyboard = Keyboard::inlineKeyboard([
    Keyboard::inlineRow(
        Keyboard::callbackButton('👍 Like', 'like_1'),
        Keyboard::callbackButton('👎 Dislike', 'dislike_1')
    ),
    Keyboard::inlineRow(
        Keyboard::urlButton('🌐 Website', 'https://example.com')
    ),
    Keyboard::inlineRow(
        Keyboard::switchQueryButton('🔍 Search', 'query')
    )
]);

// Send with keyboard
$bot->sendMessage($chatId, 'Choose an option:', [
    'reply_markup' => json_encode($keyboard)
]);

Button Types

Keyboard::callbackButton('Text', 'callback_data');   // Callback button
Keyboard::urlButton('Text', 'https://...');      // URL button
Keyboard::switchQueryButton('Text', 'query');  // Switch to inline query
Keyboard::loginButton('Login', 'https://...'); // Login URL button

⌨️ Reply Keyboards

// Reply keyboard (persistent)
$keyboard = Keyboard::replyKeyboard([
    Keyboard::inlineRow('📢 Channel', '👤 Profile'),
    Keyboard::inlineRow('⚙️ Settings', '❓ Help')
], true, true);  // resize, one_time

$bot->sendMessage($chatId, 'Menu:', [
    'reply_markup' => json_encode($keyboard)
]);

// Remove keyboard
$keyboard = Keyboard::removeKeyboard();
$bot->sendMessage($chatId, 'Keyboard removed', [
    'reply_markup' => json_encode($keyboard)
]);

🔄 Handling Updates

use Telegram\Update;

// From webhook or getUpdates
$update = Update::fromJson($jsonString);

// Get message
$message = $update->getMessage();
if ($message) {
    $text = $message->getText();
    $chatId = $message->getChatId();
    $userId = $message->getUserId();
    
    // Check if command like /start
    if ($message->isCommand()) {
        $command = $message->getCommand();  // "/start"
        $args = $message->getArgs();       // ["arg1", "arg2"]
    }
}

// Handle callback query
$callback = $update->getCallbackQuery();
if ($callback) {
    $data = $callback->getData();
    $userId = $callback->getFrom()->getId();
    
    // Answer callback
    $bot->answerCallbackQuery($callback->getId(), 'Clicked!', true);
}

❓ Answering Queries

// Callback query (button click)
$bot->answerCallbackQuery($callbackId, 'Message', false);
$bot->answerCallbackQuery($callbackId, 'Alert!', true); // Show alert

// Inline query (bot mentioned in chat)
$results = [
    [
        'type' => 'article',
        'id' => '1',
        'title' => 'Result 1',
        'description' => 'Description',
        'input_message_content' => ['message_text' => 'Content']
    ]
];
$bot->answerInlineQuery($inlineQueryId, $results, 300);

// Pre checkout query (payment)
$bot->answerPreCheckoutQuery($queryId, true);

// Shipping query (shipping options)
$bot->answerShippingQuery($queryId, true, [
    'id' => '1',
    'title' => 'Shipping',
    'prices' => [['label' => 'Shipping', 'amount' => 500]]
]);

👥 Chat Management

// Get chat info
$chat = $bot->getChat($chatId);

// Administrators
$admins = $bot->getChatAdministrators($chatId);
$count = $bot->getChatMemberCount($chatId);
$member = $bot->getChatMember($chatId, $userId);

// Ban/Unban user
$bot->banChatMember($chatId, $userId);
$bot->banChatMember($chatId, $userId, time() + 3600); // 1 hour
$bot->unbanChatMember($chatId, $userId);

// Restrict/Promote
$bot->restrictChatMember($chatId, $userId, [
    'can_send_messages' => true
]);
$bot->promoteChatMember($chatId, $userId, [
    'can_delete_messages' => true
]);

🔗 Invite Links

// Export current link
$link = $bot->exportChatInviteLink($chatId);

// Create new link
$newLink = $bot->createChatInviteLink($chatId, time() + 3600, 10);
// Expires in 1 hour, max 10 members

// Revoke link
$bot->revokeChatInviteLink($chatId, $inviteLink);

// Approve/Decline join request
$bot->approveChatJoinRequest($chatId, $userId);
$bot->declineChatJoinRequest($chatId, $userId);

✏️ Message Editing

// Edit text
$bot->editMessageText($chatId, $messageId, 'New text', [
    'reply_markup' => json_encode($keyboard)
]);

// Edit caption
$bot->editMessageCaption($chatId, $messageId, 'New caption');

// Edit inline keyboard
$bot->editMessageReplyMarkup($chatId, $messageId, $replyMarkup);

// Delete message
$bot->deleteMessage($chatId, $messageId);

// Pin/Unpin message
$bot->pinChatMessage($chatId, $messageId);
$bot->unpinChatMessage($chatId);
$bot->unpinAllChatMessages($chatId);

📍 Location & Contact

// Location
$bot->sendLocation($chatId, 40.7128, -74.0060);

// Venue (location with address)
$bot->sendVenue($chatId, 40.7128, -74.0060, 'Venue Name', 'Address');

// Contact
$bot->sendContact($chatId, '+1234567890', 'John', [
    'last_name' => 'Doe'
]);

📊 Polls & Dice

// Poll
$bot->sendPoll($chatId, 'Question?', ['Yes', 'No', 'Maybe']);
$bot->sendPoll($chatId, 'Quiz?', ['A', 'B'], false, 'quiz');

// Dice (random emoji)
$bot->sendDice($chatId, '🎲');  // Default dice
$bot->sendDice($chatId, '🎰');  // Slot machine
$bot->sendDice($chatId, '🏀');  // Basketball
$bot->sendDice($chatId, '⚽');  // Football
$bot->sendDice($chatId, '🎳');  // Bowling

🪝 Webhooks

// Set webhook
$bot->setWebhook('https://example.com/webhook');
$bot->setWebhook('https://example.com/webhook', [
    'certificate' => '/path/to/cert.pem'
]);

// Delete webhook
$bot->deleteWebhook();

// Get webhook info
$info = $bot->getWebhookInfo();

// Handle webhook (example)
$update = Update::fromJson(file_get_contents('php://input'));

// Process update
$message = $update->getMessage();
if ($message) {
    $bot->sendMessage($message->getChatId(), 'echo: ' . $message->getText());
}

📁 File Operations

// Get file info
$file = $bot->getFile($fileId);
$filePath = $file['result']['file_path'];

// Get direct file URL
$url = $bot->getFileUrl($filePath);

// Download file
$bot->downloadFile($filePath, '/save/path/file.ext');

🤖 Bot Commands

// Set commands (shows in menu)
$bot->setMyCommands([
    ['command' => 'start', 'description' => 'Start the bot'],
    ['command' => 'help', 'description' => 'Show help'],
    ['command' => 'settings', 'description' => 'Settings'],
    ['command' => 'ping', 'description' => 'Pong!']
]);

// Get commands
$commands = $bot->getMyCommands();

// Delete commands
$bot->deleteMyCommands();

ℹ️ Bot Info

// Get bot info
$me = $bot->getMe();

// Get/set bot name
$name = $bot->getMyName();
$bot->setMyName('My Bot');

// Get/set description
$desc = $bot->getMyDescription();
$bot->setMyDescription('Bot description');

// Get/set short description
$short = $bot->getMyShortDescription();
$bot->setMyShortDescription('Short desc');

🔄 Forwarding & Copying

// Forward message
$bot->forwardMessage($toChatId, $fromChatId, $messageId);

// Copy message
$bot->copyMessage($toChatId, $fromChatId, $messageId);

// Copy multiple messages
$bot->copyMessages($toChatId, $fromChatId, [$msg1, $msg2, $msg3]);

📋 Example: echo Bot

<?php
require_once __DIR__ . '/src/Bot.php';
require_once __DIR__ . '/src/Update.php';

use Telegram\Bot;

$bot = new Bot('YOUR_BOT_TOKEN');

// Get input
$update = Update::fromJson(file_get_contents('php://input'));

$message = $update->getMessage();
if ($message) {
    $text = $message->getText();
    $chatId = $message->getChatId();
    
    // Echo the message
    $bot->sendMessage($chatId, $text);
}

// Or use getUpdates loop:
while (true) {
    $updates = $bot->getUpdates();
    foreach ($updates['result'] as $update) {
        // Process...
    }
    sleep(1);
}

📋 Example: Command Handler

<?php
require_once __DIR__ . '/src/Bot.php';
require_once __DIR__ . '/src/Keyboard.php';
require_once __DIR__ . '/src/Update.php';

use Telegram\Bot;
use Telegram\Keyboard;

$bot = new Bot('YOUR_BOT_TOKEN');
$update = Update::fromJson(file_get_contents('php://input'));
$message = $update->getMessage();

if (!$message) exit;

$chatId = $message->getChatId();
$text = $message->getText();
$command = $message->getCommand();
$args = $message->getArgs();

switch ($command) {
    case '/start':
        $bot->sendMessage($chatId, '👋 Welcome! Use /help');
        break;
    
    case '/help':
        $help = "Available commands:\n/start - Start\n/help - Help";
        $bot->sendMessage($chatId, $help);
        break;
    
    case '/ping':
        $bot->sendMessage($chatId, '🏓 Pong!');
        break;
    
    case '/info':
        $chat = $bot->getChat($chatId);
        $info = "Chat: " . $chat->getTitle();
        $bot->sendMessage($chatId, $info);
        break;
        
    default:
        // Echo message
        $bot->sendMessage($chatId, $text);
}

📋 Example: Callback Handler

<?php
require_once __DIR__ . '/src/Bot.php';
require_once __DIR__ . '/src/Update.php';

use Telegram\Bot;
use Telegram\Keyboard;

$bot = new Bot('YOUR_BOT_TOKEN');
$update = Update::fromJson(file_get_contents('php://input'));

$callback = $update->getCallbackQuery();
if ($callback) {
    $data = $callback->getData();
    $message = $callback->getMessage();
    $chatId = $message->getChatId();
    $messageId = $message->getMessageId();
    
    switch ($data) {
        case 'like':
            // Update message
            $bot->editMessageCaption($chatId, $messageId, '👍 Liked!');
            $bot->answerCallbackQuery($callback->getId(), 'Liked! 🎉');
            break;
            
        case 'dislike':
            $bot->editMessageCaption($chatId, $messageId, '👎 Disliked');
            $bot->answerCallbackQuery($callback->getId(), 'Disliked 😢');
            break;
    }
}

🔗 Links

📦 Download: Get the library on GitHub

Made with ❤️ for Telegram Bot development