PHPackages                             texhub/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. texhub/telegram

ActiveLibrary[API Development](/categories/api)

texhub/telegram
===============

Full-featured, multi-tenant Telegram Bot API &amp; Telegram Business SDK for any PHP framework with first-class Laravel support: messages, media, keyboards, webhooks, long polling and more.

v1.9.1(1mo ago)04MITPHPPHP ^8.2

Since Jun 1Pushed 1mo agoCompare

[ Source](https://github.com/TexhubPro/telegram)[ Packagist](https://packagist.org/packages/texhub/telegram)[ Docs](https://texhub.pro)[ RSS](/packages/texhub-telegram/feed)WikiDiscussions main Synced 1w ago

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

TexHub · Telegram
=================

[](#texhub--telegram)

**English** · [Русский](README.ru.md)

[![License: MIT](https://camo.githubusercontent.com/7013272bd27ece47364536a221edb554cd69683b68a46fc0ee96881174c4214c/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6c6963656e73652d4d49542d626c75652e737667)](LICENSE)[![PHP](https://camo.githubusercontent.com/d91d3d1139cf0d8faaa80eeeeac7d3c59c9319e56960ef81c948e4160be4c4c1/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f7068702d253545382e322d3737376262342e737667)](composer.json)[![Laravel](https://camo.githubusercontent.com/3e9242504354dbb5afd360f9a1ec114126b2caddb73d9e789d9102c3285d2b05/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6c61726176656c2d3131253230253743253230313225323025374325323031332d6666326432302e737667)](#laravel)

A full-featured, **multi-tenant** Telegram **Bot API** &amp; **Telegram Business** SDK for any PHP framework — built to be **beginner-friendly**: write a method named after each command, reply with a fluent `$this->chat`, and manage bots from the terminal.

> The **entire Bot API** is reachable via `->call()`, with typed helpers and builders for the common cases. Secure by default: webhook secret-token verification and token scrubbing in errors.

> **[Full method reference &amp; cookbook →](docs/REFERENCE.md)** — every method with copy-paste examples and example responses.

Reference:

---

Features
--------

[](#features)

- **Easy bot builder** — extend `UpdateHandler`, write `public function start()` for `/start`
- **Fluent replies** — `$this->chat->message('Hi')->html()->keyboard(...)->send()`
- **Keyboards** — inline &amp; reply builders, every button type (web app, **copy text**, login, …)
- **Messages &amp; media** — text, photo, video, audio, voice, document, sticker, location, contact, poll, dice
- **Edit / delete / forward / copy**, reactions, pin, chat actions
- **Files** — upload local files, `getFile`, download bytes/to disk
- **Payments** (invoices &amp; Telegram Stars) and **Games**
- **Webhooks** — secret-token verification + a rich `Update` parser for everything that arrives
- **Telegram Business** — business updates + send on behalf of a connection
- **Multi-tenant** — many bots; store them (and every chat) in your DB
- **Artisan commands** — add bots, set/unset webhooks, list bots
- **Full coverage** — `->call('anyMethod', [...])` for everything else; fully unit-tested

---

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

[](#installation)

```
composer require texhub/telegram
```

Requirements: **PHP ≥ 8.2** with `curl`, `json`, `hash`.

---

Build a bot (the easy way)
--------------------------

[](#build-a-bot-the-easy-way)

Extend `UpdateHandler` and write a method **named after each command**. The argument is whatever follows it (e.g. a referral code from `/start REF123`). Reply with the fluent `$this->chat`:

```
use TexHub\Telegram\Handler\UpdateHandler;
use TexHub\Telegram\Keyboard\InlineKeyboard;
use TexHub\Telegram\Keyboard\Button;

class MyBot extends UpdateHandler
{
    // "/start"  →  start();   "/start REF123"  →  start('REF123')
    public function start(string $payload = ''): void
    {
        if ($payload !== '') {
            $this->chat->message("Invited with code: {$payload}")->send();   // who invited
        }

        $this->chat->message('Welcome! 👋')
            ->keyboard(InlineKeyboard::make()->row(Button::callback('Menu', 'menu')))
            ->send();
    }

    public function help(): void                  { $this->chat->message('Send /start')->send(); }
    public function onText(string $text): void    { $this->chat->message('You said: ' . $text)->send(); }
    public function onPhoto(): void               { $this->chat->message('Nice photo!')->send(); }
    public function onContact(array $c): void      { $this->chat->message('📱 ' . $c['phone_number'])->send(); }
    public function onLocation(array $l): void     { $this->chat->message("📍 {$l['latitude']}, {$l['longitude']}")->send(); }
    public function onCallbackQuery(array $cb): void { $this->answerCallback('OK'); }
}
```

Wire it in your webhook — one line (it verifies the secret, parses and dispatches):

```
(new MyBot)->handleRequest($bot, $request->getContent(), $request->header('X-Telegram-Bot-Api-Secret-Token'));
```

Override `onText`, `onPhoto`, `onVideo`, `onDocument`, `onVoice`, `onAudio`, `onAnimation`, `onSticker`, `onLocation`, `onContact`, `onCallbackQuery`, `onInlineQuery`, `onPreCheckoutQuery`, `onMessage`, `onOther` — and any `commandName()`.

---

Sending directly (without a handler)
------------------------------------

[](#sending-directly-without-a-handler)

```
use TexHub\Telegram\Telegram;
use TexHub\Telegram\Keyboard\InlineKeyboard;
use TexHub\Telegram\Keyboard\Button;
use TexHub\Telegram\InputFile;

$bot = Telegram::bot('123456:ABC-TOKEN');

// Fluent:
$bot->chat($chatId)->message('Hello world')->html()->send();
$bot->chat($chatId)->photo(InputFile::fromPath('/path/pic.jpg'))->caption('Look')->send();
$bot->chat($chatId)
    ->message('Choose:')
    ->keyboard(InlineKeyboard::make()->row(
        Button::callback('✅ Yes', 'yes'),
        Button::copyText('📋 Copy code', 'PROMO-2026'),
        Button::webApp('🚀 Open app', 'https://app.texhub.pro'),
    ))
    ->send();

// Classic:
$bot->sendMessage($chatId, 'Hi', ['parse_mode' => 'HTML']);
$bot->sendPhoto($chatId, 'https://example.com/pic.jpg', ['caption' => 'Photo']);
$bot->downloadFileTo($fileId, '/path/save.jpg');

// Anything in the Bot API:
$bot->call('banChatMember', ['chat_id' => $chatId, 'user_id' => $userId]);
```

See the **[full reference](docs/REFERENCE.md)** for every method (payments, games, chat admin, …).

---

Webhooks
--------

[](#webhooks)

```
$bot->setWebhook('https://app.tj/telegram/webhook', [
    'secret_token' => 'your-secret',
    'allowed_updates' => ['message', 'callback_query', 'business_message'],
    'drop_pending_updates' => true,
]);
$bot->unsetWebhook();
$bot->getWebhookInfo();
```

The incoming `Update` exposes **everything**: `text()`, `photo()/photoFileId()`, `video()`, `document()`, `voice()`, `audio()`, `animation()`, `sticker()`, `location()`, `contact()`, `venue()`, `poll()`, `dice()`, `caption()`, `chatId()`, `fromId()`, `messageId()`, `fileId()`, `callbackQuery()`, `isCommand()`, `isBusiness()`, `businessConnectionId()`.

---

Telegram Business
-----------------

[](#telegram-business)

```
if ($update->isBusiness()) {
    $bot->asBusiness($update->businessConnectionId())
        ->sendMessage($update->chatId(), 'Reply on behalf of the business');
}
```

---

Multi-tenant (many bots)
------------------------

[](#multi-tenant-many-bots)

```
$tg = Telegram::fromArray([
    'default' => 'support',
    'bots' => ['support' => ['token' => '111:AAA'], 'sales' => ['token' => '222:BBB']],
]);

$tg->driver('sales')->sendMessage($chatId, 'Hi from sales');
$tg->botFromToken($tenant->telegram_token)->sendMessage($chatId, '...'); // from DB at runtime
```

---

 Laravel
-------------------------------------------

[](#-laravel)

Auto-discovered. Publish config (+ optional migrations for storing bots &amp; chats):

```
php artisan vendor:publish --tag=telegram-config
php artisan vendor:publish --tag=telegram-migrations
php artisan migrate
```

### Artisan commands

[](#artisan-commands)

```
php artisan telegram:bot:add        # interactive: token → auto-secret → set webhook → save to DB
php artisan telegram:bots           # list all bots
php artisan telegram:webhook:set {bot?} {url?}
php artisan telegram:webhook:unset {bot?} --drop-pending
php artisan telegram:webhook:info {bot?}
```

### Facade

[](#facade)

```
use TexHub\Telegram\Laravel\Telegram;

Telegram::sendMessage($chatId, 'Hi from Laravel!');         // default bot
Telegram::driver('sales')->chat($chatId)->message('…')->send();
```

### Models (store bots &amp; chats)

[](#models-store-bots--chats)

```
use TexHub\Telegram\Laravel\Models\TelegramBot;
use TexHub\Telegram\Laravel\Models\TelegramChat;

$record = TelegramBot::create(['name' => 'Acme', 'token' => '999:XYZ', 'webhook_secret' => '...']);
$record->client()->sendMessage($chatId, 'Hello from a tenant bot');

// Remember everyone who writes to the bot (chat_id, name, username, language, avatar…):
$chat = TelegramChat::rememberFromUpdate($update, $record->id);
$chat->refreshAvatar($record->client());
$record->chats()->where('is_active', true)->get();
```

### Webhook controller

[](#webhook-controller)

```
public function webhook(string $bot, \Illuminate\Http\Request $request)
{
    (new \App\Telegram\MyBot)->handleRequest(
        \TexHub\Telegram\Laravel\Telegram::driver($bot),
        $request->getContent(),
        $request->header('X-Telegram-Bot-Api-Secret-Token'),
    );

    return response('', 200);
}
```

> Exclude the webhook route from CSRF (`validateCsrfTokens(except: ['telegram/webhook'])`).

---

Testing
-------

[](#testing)

```
use TexHub\Telegram\Bot;
use TexHub\Telegram\Config;
use TexHub\Telegram\Tests\Support\FakeTransport;

$t = (new FakeTransport())->willReturn(['message_id' => 1, 'chat' => ['id' => 99]]);
$bot = new Bot(new Config('123:ABC'), $t);
$bot->chat(99)->message('hi')->send(); // assert on $t->last()
```

```
composer install && composer test
```

---

Architecture
------------

[](#architecture)

```
src/
├── Telegram.php             # multi-bot manager (driver/botFromToken)
├── Bot.php                  # client — call() + typed methods + chat()/asBusiness()
├── Handler/UpdateHandler.php# extend-me dispatcher (command*/on* methods)
├── Messaging/               # ChatContext + PendingMessage (fluent builder)
├── Update.php               # rich accessors for everything that arrives
├── Keyboard/                # InlineKeyboard, ReplyKeyboard, Button
├── Enums/ · Http/ · Webhook/ · Exceptions/
└── Laravel/                 # ServiceProvider, Facade, Commands/, Models (Bot + Chat), migrations

```

---

License
-------

[](#license)

MIT © TexHub Pro — built by Mahmudi Shodmehr.

###  Health Score

42

—

FairBetter than 88% of packages

Maintenance93

Actively maintained with recent releases

Popularity5

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity53

Maturing project, gaining track record

 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 ~2 days

Total

11

Last Release

34d ago

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/217647751?v=4)[TexHub Pro](/maintainers/TexhubPro)[@TexhubPro](https://github.com/TexhubPro)

---

Top Contributors

[![TexhubPro](https://avatars.githubusercontent.com/u/217647751?v=4)](https://github.com/TexhubPro "TexhubPro (13 commits)")

---

Tags

bot-apilaravelphpsdktelegramtelegram-bottelegram-businesswebhooksphplaravelwebhookstelegrambot apitelegram botmulti-tenanttexhubtelegram-business

###  Code Quality

TestsPHPUnit

### Embed Badge

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

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

###  Alternatives

[klev-o/telegram-bot-api

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

468.5k1](/packages/klev-o-telegram-bot-api)

PHPackages © 2026

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