PHPackages                             fardadev/telegram-objects-php - 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. fardadev/telegram-objects-php

ActiveLibrary[API Development](/categories/api)

fardadev/telegram-objects-php
=============================

Framework-agnostic PHP library providing strongly-typed Telegram Bot API DTOs and objects

v0.1.0-beta(6mo ago)61[2 PRs](https://github.com/FardaDev/telegram-objects-php/pulls)MITPHPPHP ^8.1CI passing

Since Nov 6Pushed 1mo agoCompare

[ Source](https://github.com/FardaDev/telegram-objects-php)[ Packagist](https://packagist.org/packages/fardadev/telegram-objects-php)[ Docs](https://github.com/FardaDev/telegram-objects-php)[ RSS](/packages/fardadev-telegram-objects-php/feed)WikiDiscussions main Synced 1mo ago

READMEChangelogDependencies (4)Versions (4)Used By (0)

Telegram Objects PHP
====================

[](#telegram-objects-php)

[![Tests](https://github.com/FardaDev/telegram-objects-php/actions/workflows/tests.yml/badge.svg)](https://github.com/FardaDev/telegram-objects-php/actions/workflows/tests.yml)[![Coverage](https://github.com/FardaDev/telegram-objects-php/actions/workflows/coverage.yml/badge.svg)](https://github.com/FardaDev/telegram-objects-php/actions/workflows/coverage.yml)[![Security](https://github.com/FardaDev/telegram-objects-php/actions/workflows/security.yml/badge.svg)](https://github.com/FardaDev/telegram-objects-php/actions/workflows/security.yml)[![PHP Version](https://camo.githubusercontent.com/cc9cdea9aa96b40a822425e981b0a030e3371202973c7d57b74e8e99834f81dc/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f7068702d253545382e312d626c7565)](https://php.net)[![License](https://camo.githubusercontent.com/f8df3091bbe1149f398a5369b2c39e896766f9f6efba3477c63e9b4aa940ef14/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6c6963656e73652d4d49542d677265656e)](LICENSE)

**A solid foundation for building Telegram bots in PHP.**

This library provides strongly-typed, immutable DTOs (Data Transfer Objects) for the Telegram Bot API. It's designed as a **base layer** that other PHP libraries and frameworks can build upon, offering robust object representations without magic methods or dynamic properties.

Why This Library?
-----------------

[](#why-this-library)

**For Library Authors:**

- Build your Telegram bot framework on a solid, type-safe foundation
- No need to reimplement DTOs - focus on your unique features
- Stable API that follows Telegram's official types

**For Bot Developers:**

- **🚀 Zero Dependencies** - No framework lock-in, works anywhere
- **💪 Type-Safe** - Full PHP 8.1+ strict typing with readonly properties
- **📦 Complete** - 37 DTOs, 5 enums, 4 keyboard builders, 6 exceptions
- **✅ Well-Tested** - 506 tests with comprehensive coverage
- **🎯 Modern PHP** - Uses enums, match expressions, named arguments
- **📖 Well-Documented** - Extensive docs and working examples

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

[](#installation)

```
composer require fardadev/telegram-objects-php
```

**Requirements:** PHP 8.1+

Quick Start
-----------

[](#quick-start)

### Parse Telegram Webhooks

[](#parse-telegram-webhooks)

```
use Telegram\Objects\DTO\TelegramUpdate;

// Parse incoming webhook
$update = TelegramUpdate::fromArray(
    json_decode(file_get_contents('php://input'), true)
);

// Access message data
if ($update->message()) {
    $text = $update->message()->text();
    $user = $update->message()->from();

    echo "{$user->firstName()}: {$text}";
}

// Handle button clicks
if ($update->callbackQuery()) {
    $data = $update->callbackQuery()->data();
    $user = $update->callbackQuery()->from();

    echo "{$user->firstName()} clicked: {$data}";
}
```

### Create DTOs

[](#create-dtos)

```
use Telegram\Objects\DTO\User;
use Telegram\Objects\DTO\Message;

// From array (Telegram API response)
$user = User::fromArray([
    'id' => 123456789,
    'first_name' => 'John',
    'last_name' => 'Doe',
    'username' => 'johndoe',
    'is_bot' => false
]);

// Access properties
echo $user->fullName();  // "John Doe"
echo $user->id();        // 123456789
echo $user->isBot();     // false

// Convert back to array
$array = $user->toArray();
```

### Build Keyboards

[](#build-keyboards)

```
use Telegram\Objects\Keyboard\Keyboard;
use Telegram\Objects\Keyboard\Button;

// Inline keyboard
$keyboard = Keyboard::make()
    ->row([
        Button::make('Visit Site')->url('https://example.com'),
        Button::make('Contact')->action('contact_support')
    ])
    ->row([
        Button::make('Settings')->action('settings')
    ]);

// Use in Telegram API request
$response = [
    'chat_id' => $chatId,
    'text' => 'Choose an option:',
    'reply_markup' => [
        'inline_keyboard' => $keyboard->toArray()
    ]
];
```

```
use Telegram\Objects\Keyboard\ReplyKeyboard;
use Telegram\Objects\Keyboard\ReplyButton;

// Reply keyboard
$keyboard = ReplyKeyboard::make()
    ->row([
        ReplyButton::make('📱 Share Contact')->requestContact(),
        ReplyButton::make('📍 Share Location')->requestLocation()
    ])
    ->resize()
    ->oneTime();

// Use in Telegram API request
$response = [
    'chat_id' => $chatId,
    'text' => 'Share your info:',
    'reply_markup' => $keyboard->toArray()
];
```

What's Included
---------------

[](#whats-included)

### 37 Data Transfer Objects

[](#37-data-transfer-objects)

**Core:** `TelegramUpdate`, `Message`, `User`, `Chat`
**Media:** `Photo`, `Video`, `Audio`, `Voice`, `Document`, `Animation`, `Sticker`
**Interactive:** `CallbackQuery`, `InlineQuery`, `Poll`, `PollAnswer`
**Payments:** `Invoice`, `SuccessfulPayment`, `PreCheckoutQuery`
**Admin:** `ChatMember`, `ChatInviteLink`, `ChatJoinRequest`
**More:** `Location`, `Contact`, `Venue`, `Entity`, `Reaction`, and more

[See full list →](docs/api-reference.md)

### 5 Enums

[](#5-enums)

```
use Telegram\Objects\Enums\ChatActions;
use Telegram\Objects\Enums\ChatPermissions;
use Telegram\Objects\Enums\Emojis;

ChatActions::TYPING;
ChatPermissions::CAN_SEND_MESSAGES;
Emojis::THUMBS_UP;
```

### 4 Keyboard Builders

[](#4-keyboard-builders)

- `Keyboard` - Inline keyboards with callbacks, URLs, web apps
- `Button` - Inline keyboard buttons
- `ReplyKeyboard` - Reply keyboards with custom buttons
- `ReplyButton` - Reply keyboard buttons with special requests

### 6 Exception Types

[](#6-exception-types)

```
use Telegram\Objects\Exceptions\ValidationException;
use Telegram\Objects\Exceptions\TelegramException;

try {
    $user = User::fromArray($data);
} catch (ValidationException $e) {
    // Handle validation errors
}
```

Documentation
-------------

[](#documentation)

- **[Getting Started](docs/getting-started.md)** - Installation and basic usage
- **[API Reference](docs/api-reference.md)** - Complete DTO documentation
- **[Keyboards Guide](docs/keyboards.md)** - Building inline and reply keyboards
- **[Examples](examples/)** - Working code examples
- **[Contributing](docs/contributing.md)** - How to contribute

Examples
--------

[](#examples)

Check the [`examples/`](examples/) directory for complete working examples:

- **[basic-usage.php](examples/basic-usage.php)** - Creating and using DTOs
- **[webhook-parsing.php](examples/webhook-parsing.php)** - Parsing Telegram webhooks
- **[keyboard-examples.php](examples/keyboard-examples.php)** - Building keyboards

Testing
-------

[](#testing)

```
# Run all tests
composer test

# Run specific tests
composer test:unit      # Unit tests
composer test:types     # Static analysis (PHPStan level 8)
composer test:lint      # Code style (PSR-12)

# Generate coverage
composer coverage
```

Features
--------

[](#features)

### Type Safety

[](#type-safety)

```
// Full IDE autocompletion and type checking
$update = TelegramUpdate::fromArray($data);
$messageId = $update->message()?->id();        // int|null
$text = $update->message()?->text();           // string
$userId = $update->message()?->from()?->id();  // int|null
```

### Immutability

[](#immutability)

All DTOs are immutable (readonly properties) - safe for concurrent use.

### Validation

[](#validation)

Built-in validation when creating from arrays:

```
// Throws ValidationException if required fields missing
$message = Message::fromArray($data);
```

### Framework Agnostic

[](#framework-agnostic)

Works with any PHP framework or vanilla PHP:

- ✅ Laravel
- ✅ Symfony
- ✅ Slim
- ✅ Pure PHP
- ✅ Any framework

Attribution
-----------

[](#attribution)

Inspired by and adapted from [DefStudio/Telegraph](https://github.com/defstudio/telegraph), chosen for its robust DTO architecture that avoids magic methods and dynamic properties in favor of explicit, type-safe objects.

All source files include proper attribution headers tracking the original Telegraph files and commit hashes. Development assisted by [Kiro AI IDE](https://kiro.ai).

License
-------

[](#license)

MIT License - see [LICENSE](LICENSE) file.

Support
-------

[](#support)

- **Issues:** [GitHub Issues](https://github.com/FardaDev/telegram-objects-php/issues)
- **Discussions:** [GitHub Discussions](https://github.com/FardaDev/telegram-objects-php/discussions)
- **Changelog:** [CHANGELOG.md](CHANGELOG.md)

---

Made with ❤️ by [FardaDev](https://github.com/FardaDev)

###  Health Score

33

—

LowBetter than 75% of packages

Maintenance80

Actively maintained with recent releases

Popularity6

Limited adoption so far

Community8

Small or concentrated contributor base

Maturity32

Early-stage or recently created project

 Bus Factor1

Top contributor holds 88.9% 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

Unknown

Total

1

Last Release

193d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/5cf4dd3156a33cb44ee6538dc5dd6210f6280766b0711ce235e584785e75301c?d=identicon)[MansourM](/maintainers/MansourM)

---

Top Contributors

[![MansourM](https://avatars.githubusercontent.com/u/22474418?v=4)](https://github.com/MansourM "MansourM (56 commits)")[![dependabot[bot]](https://avatars.githubusercontent.com/in/29110?v=4)](https://github.com/dependabot[bot] "dependabot[bot] (7 commits)")

---

Tags

phpapibottelegramdtoframework agnostic

###  Code Quality

TestsPest

Static AnalysisPHPStan

Code StylePHP CS Fixer

Type Coverage Yes

### Embed Badge

![Health badge](/badges/fardadev-telegram-objects-php/health.svg)

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

###  Alternatives

[borsaco/telegram-bot-api-bundle

A simple wrapper for telegram-bot-api.

5633.0k](/packages/borsaco-telegram-bot-api-bundle)[klev-o/telegram-bot-api

Simple and convenient object-oriented implementation Telegram bot API with php version ^7.4 support. You'll like it)

457.8k1](/packages/klev-o-telegram-bot-api)[klev-o/crypto-pay-api

Simple and convenient implementation of the Crypto Pay payment system (@CryptoBot)

205.1k](/packages/klev-o-crypto-pay-api)[kuvardin/telegram-bots-api

SDK for Telegram bots API

145.5k](/packages/kuvardin-telegram-bots-api)

PHPackages © 2026

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