PHPackages                             yabx/telegram - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [API Development](/categories/api)
4. /
5. yabx/telegram

ActiveLibrary[API Development](/categories/api)

yabx/telegram
=============

Telegram Bot API SDK for PHP 8.1+

10.1.1(2w ago)23.1k↓49.2%1MITPHPPHP &gt;=8.1CI passing

Since Mar 28Pushed 2w ago1 watchersCompare

[ Source](https://github.com/yabx-net/telegram)[ Packagist](https://packagist.org/packages/yabx/telegram)[ RSS](/packages/yabx-telegram/feed)WikiDiscussions master Synced 2d ago

READMEChangelogDependencies (8)Versions (38)Used By (1)

yabx/telegram
=============

[](#yabxtelegram)

PHP SDK for the [Telegram Bot API](https://core.telegram.org/bots/api). Typed request/response objects, [Guzzle](https://github.com/guzzle/guzzle) HTTP client, and coverage aligned with **Bot API 10.1** (June 2026).

Requirements
------------

[](#requirements)

- PHP `>= 8.1`
- Extensions: `json`, `curl`
- Composer dependencies: `guzzlehttp/guzzle` `^7.9`, `psr/log` `^3.0`

Installation
------------

[](#installation)

```
composer require yabx/telegram
```

Features
--------

[](#features)

- Strongly typed **`Yabx\Telegram\Objects\*`** models for [available types](https://core.telegram.org/bots/api#available-types)
- One method per Bot API method on **`Yabx\Telegram\BotApi`**, matching [available methods](https://core.telegram.org/bots/api#available-methods)
- **`request()`** for direct API calls when you need maximum flexibility
- Optional **PSR-3** logging and custom **Guzzle** / base URL for tests or proxies
- Webhook parsing from raw JSON or **`php://input`**
- **`getUpdates`** long polling support

Quick start
-----------

[](#quick-start)

```
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'));
```

### Client options

[](#client-options)

```
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
);
```

### Send messages (text, parse mode, reply)

[](#send-messages-text-parse-mode-reply)

```
use Yabx\Telegram\Objects\ReplyParameters;

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

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

### Inline keyboard

[](#inline-keyboard)

```
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);
```

### Reply keyboard (custom keyboard)

[](#reply-keyboard-custom-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);
```

### Photo from disk (multipart upload)

[](#photo-from-disk-multipart-upload)

If the path exists on disk, the client opens the file and sends it as **multipart** automatically:

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

### Webhooks

[](#webhooks)

Register and inspect the webhook:

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

$info = $bot->getWebhookInfo();
```

Handle an incoming POST body (typical PHP endpoint):

```
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);
```

Then branch on the update payload:

```
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');
}
```

### Long polling (`getUpdates`)

[](#long-polling-getupdates)

```
$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() ?? ''));
        }
    }
}
```

### Low-level `request()`

[](#low-level-request)

Useful for new API parameters before a dedicated method exists, or rare calls:

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

Objects with a `toArray()` method are normalized automatically. Upload methods on `BotApi` already set `multipart` where needed.

### Last raw API response

[](#last-raw-api-response)

After each call, the decoded JSON envelope (including `ok`, `result`, `description`, etc.) is available:

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

### Error handling

[](#error-handling)

Failed Bot API responses throw **`Yabx\Telegram\Exception`** with Telegram’s **`error_code`** as the exception code when present:

```
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());
}
```

Project layout
--------------

[](#project-layout)

PathRole`src/BotApi.php`Client: all Bot API methods + `request()``src/Objects/`Telegram types (`Message`, `Update`, keyboards, …)`src/Enum/`Helpers such as `ChatAction`, etc.`tests/`PHPUnit test suite and JSON fixturesTesting
-------

[](#testing)

```
composer install
composer test
```

Optional coverage report (requires the [PCOV](https://github.com/krakjoe/pcov) extension locally):

```
# Ubuntu/Debian — match your PHP version (php -v)
sudo apt install php8.3-pcov   # or php8.5-pcov, php8.2-pcov, …

composer test:coverage
```

HTML report in `build/coverage/`:

```
composer test:coverage-html
```

If PCOV is not installed, `composer test:coverage` prints installation hints instead of a cryptic PHPUnit error. CI collects coverage with PCOV on PHP 8.3 (job `coverage` in `.github/workflows/tests.yml`).

Tests use [PHPUnit](https://phpunit.de/) 10.5+ (PHP 8.1) or 11+ (PHP 8.2+) with Guzzle `MockHandler` for HTTP integration tests. Fixtures live in `tests/Fixtures/`.

### Coverage phases

[](#coverage-phases)

PhaseScopeStatus1Infrastructure, `Utils`, `BotApi`, core objectsdone2All `RichText` / `RichBlock` types, update variantsdone3Polymorphic dispatchers (`ChatMember`, `MessageOrigin`, …)done4Round-trip manifest (`tests/Fixtures/roundtrip/`)done — 331 leaf classes (~93%); dispatchers tested separately5Composite variant tests (`ChatFullInfo`, `Message`, `ExternalReplyInfo`)done6All `Update` webhook variantsdone — 22 fixtures7`BotApi` integration (request serialization, response parsing)done — 57 tests8Composite variants (`Message` quote/forward, `ExternalReplyInfo` media)done9API response snapshots (`tests/Fixtures/api_responses/`)done — 7 fixtures10Shared `MocksBotApi` trait, multipart uploads, forum topic variantsdone11Media send methods, payments, `ChatFullInfo` private, service messagesdone12Location/contact/video note, stars, migration/members, `getUpdatefromRequest`done13Paid media, batch delete/copy, `ChatBoostSource` dispatcher, chat service messagesdone14Chat actions, reactions, join requests, sticker set snapshot, chat event messagesdone15Live location, menu button, custom emoji, invite link snapshot, `Update` round-tripdone16Live photo, forum topics, games, restrict member, service message variantsdone — 79 BotApi tests, 13 snapshots17Chat admin, forum/general topics, stickers, bot profile/commands, join-querydone — 113 BotApi tests, ~69% `BotApi.php` lines18Business, stories, gifts/stars, payments, verification, managed bot, `downloadFile`done — 127 BotApi tests, ~99% `BotApi.php` lines19Deep `Message` / `ChatFullInfo` / `Update` variantsdone — 42 message fixtures, `Message` ~67% lines20`BotApi` edge cases: multipart, `downloadFile`, logging, transport errorsdone — `BotApiEdgeCasesTest`21API snapshots: business, gifts, boosts, invoice, extended chatdone — 18 snapshots22Polymorphic dispatch + `sendPoll` / `InputPollMedia` contractdone23PHPStan level 2, coverage threshold 57%, CI static analysisdone — `composer phpstan`24`CHANGELOG.md`, README examples for Bot API 10.1 featuresdone`InputPollMedia` / `InputPollOptionMedia` are PHP interfaces; implementing classes (`InputMediaPhoto`, `InputMediaLink`, …) are covered in the round-trip manifest and via `sendPoll` contract tests.

### Static analysis and coverage gate

[](#static-analysis-and-coverage-gate)

```
composer phpstan          # PHPStan level 2 on src/
composer test:coverage    # fails if line coverage drops below 57%
```

### Bot API 10.1 examples

[](#bot-api-101-examples)

**Business connection**

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

**Stories (managed business account)**

```
use Yabx\Telegram\Objects\InputStoryContentPhoto;

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

**Gifts and Stars**

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

**Rich messages**

```
use Yabx\Telegram\Objects\InputRichMessage;

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

To add coverage for a new object, append an entry to the appropriate file under `tests/Fixtures/roundtrip/` (merged by `roundtrip.php`):

```
SomeObject::class => ['field' => 'value'],
```

License
-------

[](#license)

**MIT** (see [`composer.json`](composer.json)).

See also
--------

[](#see-also)

- [Telegram Bot API documentation](https://core.telegram.org/bots/api)
- [Creating a bot with BotFather](https://core.telegram.org/bots/tutorial)

###  Health Score

52

—

FairBetter than 96% of packages

Maintenance96

Actively maintained with recent releases

Popularity24

Limited adoption so far

Community9

Small or concentrated contributor base

Maturity66

Established project with proven stability

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~32 days

Recently: every ~9 days

Total

37

Last Release

19d ago

Major Versions

0.5.3 → 7.9.02024-08-22

7.10.4 → 8.0.02024-11-20

8.1.2 → 9.6.02026-05-08

9.6.0 → 10.0.02026-05-11

PHP version history (2 changes)0.1.0PHP &gt;=8.0

0.3.0PHP &gt;=8.1

### Community

Maintainers

![](https://www.gravatar.com/avatar/63879dd901c9fe1b39a20e7847dbc93d69c19a8b3e7e7480bca1a993df1e267c?d=identicon)[yauhenko](/maintainers/yauhenko)

---

Top Contributors

[![yauhenko](https://avatars.githubusercontent.com/u/4437817?v=4)](https://github.com/yauhenko "yauhenko (48 commits)")

---

Tags

apisdkbottelegramtelegram bottelegram bot apitelegram sdktelegram php

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan

Type Coverage Yes

### Embed Badge

![Health badge](/badges/yabx-telegram/health.svg)

```
[![Health](https://phpackages.com/badges/yabx-telegram/health.svg)](https://phpackages.com/packages/yabx-telegram)
```

###  Alternatives

[irazasyed/telegram-bot-sdk

The Unofficial Telegram Bot API PHP SDK

3.3k4.9M94](/packages/irazasyed-telegram-bot-sdk)[telegram-bot-sdk/telegram-bot-sdk

The Telegram Bot API PHP SDK

32981.6k](/packages/telegram-bot-sdk-telegram-bot-sdk)[eslazarev/wildberries-sdk

Wildberries OpenAPI clients (generated).

273.0k](/packages/eslazarev-wildberries-sdk)[bushlanov-dev/max-bot-api-client-php

Max Bot API Client library

486.3k](/packages/bushlanov-dev-max-bot-api-client-php)[exileed/telegram-bot-api

The Telegram Bot API PHP

1514.1k](/packages/exileed-telegram-bot-api)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
