PHP code example of yabx / telegram

1. Go to this page and download the library: Download yabx/telegram library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

yabx / telegram example snippets


use Yabx\Telegram\BotApi;

$token = getenv('TELEGRAM_BOT_TOKEN');
$bot = new BotApi($token);

$me = $bot->getMe();
$chatId = 123456789; // Telegram user/group/channel id from an allowed update context
$sent = $bot->sendMessage($chatId, 'Bot is up. Connected as @' . ($me->getUsername() ?? 'bot'));

use GuzzleHttp\RequestOptions;
use Psr\Log\LoggerInterface;
use Yabx\Telegram\BotApi;

/** @var LoggerInterface $logger e.g. Monolog, Symfony Bridge, … */
$bot = new BotApi(
    $token,
    [
        RequestOptions::TIMEOUT => 30,
        RequestOptions::VERIFY => true,
    ],
    $logger,
    'https://api.telegram.org', // optional custom API host
);

use Yabx\Telegram\Objects\ReplyParameters;

$bot->sendMessage(
    chatId: $chatId,
    text: 'Hello, <b>world</b>',
    parseMode: 'HTML',
);

$bot->sendMessage(
    chatId: $chatId,
    text: 'Replying…',
    replyParameters: new ReplyParameters(messageId: $originalMessageId),
);

use Yabx\Telegram\Objects\InlineKeyboardButton;
use Yabx\Telegram\Objects\InlineKeyboardMarkup;

$keyboard = new InlineKeyboardMarkup([
    [
        new InlineKeyboardButton('Docs', url: 'https://core.telegram.org/bots/api'),
        new InlineKeyboardButton('Tap me', callbackData: 'demo:1'),
    ],
]);

$bot->sendMessage($chatId, 'Pick an action:', replyMarkup: $keyboard);

use Yabx\Telegram\Objects\KeyboardButton;
use Yabx\Telegram\Objects\ReplyKeyboardMarkup;

$markup = new ReplyKeyboardMarkup(
    keyboard: [
        [new KeyboardButton('Yes'), new KeyboardButton('No')],
        [new KeyboardButton('Cancel')],
    ],
    resizeKeyboard: true,
    oneTimeKeyboard: true,
);

$bot->sendMessage($chatId, 'Your choice?', replyMarkup: $markup);

$bot->sendPhoto(
    chatId: $chatId,
    photo: '/tmp/snapshot.jpg',
    caption: 'Snapshot',
    parseMode: 'HTML',
);

$bot->setWebhook(
    url: 'https://example.com/telegram/webhook',
    allowedUpdates: ['message', 'callback_query'],
    secretToken: getenv('WEBHOOK_SECRET'),
);

$info = $bot->getWebhookInfo();

use Yabx\Telegram\BotApi;

// Reads php://input and builds an Update (throws if body is empty / invalid JSON)
$update = BotApi::getUpdateFromRequest();

// Or parse a string you already have:
$update = BotApi::getUpdateFromJson($requestBody);

if ($message = $update->getMessage()) {
    $chatId = $message->getChat()->getId();
    $text = $message->getText();
    $photos = $message->getPhotos();
    $video = $message->getVideo();
    $document = $message->getDocument();
    // … same pattern for stickers, polls, forwarded messages, etc.
}

if ($callback = $update->getCallbackQuery()) {
    $bot->answerCallbackQuery($callback->getId(), text: 'OK');
}

$offset = 0;

while (true) {
    $updates = $bot->getUpdates(offset: $offset, timeout: 50);

    foreach ($updates as $update) {
        $offset = $update->getUpdateId() + 1;

        if ($msg = $update->getMessage()) {
            $bot->sendMessage($msg->getChat()->getId(), 'Echo: ' . ($msg->getText() ?? ''));
        }
    }
}

$result = $bot->request('getChat', ['chat_id' => $chatId]);

$bot->sendMessage($chatId, 'Hi');
$envelope = $bot->getLastResponse();

use Yabx\Telegram\Exception as TelegramApiException;

try {
    $bot->sendMessage($chatId, 'Ping');
} catch (TelegramApiException $e) {
    // $e->getCode() often matches Telegram's error_code
    error_log($e->getMessage());
}

$connection = $bot->getBusinessConnection('bc-1');
$bot->readBusinessMessage('bc-1', $chatId, $messageId);

use Yabx\Telegram\Objects\InputStoryContentPhoto;

$bot->postStory(
    businessConnectionId: 'bc-1',
    content: new InputStoryContentPhoto(type: 'photo', photo: '/tmp/story.jpg'),
    activePeriod: 86400,
    caption: 'News',
);

$gifts = $bot->getAvailableGifts();
$bot->sendGift($userId, 'gift-id', text: 'Enjoy!');
$balance = $bot->getMyStarBalance();

use Yabx\Telegram\Objects\InputRichMessage;

$bot->sendRichMessage($chatId, new InputRichMessage(html: '<b>Hello</b>'));

SomeObject::class => ['field' => 'value'],
bash
# Ubuntu/Debian — match your PHP version (php -v)
sudo apt install php8.3-pcov   # or php8.5-pcov, php8.2-pcov, …

composer test:coverage