PHPackages                             it-healer/laravel-telegram-bot - 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. it-healer/laravel-telegram-bot

ActiveLibrary[API Development](/categories/api)

it-healer/laravel-telegram-bot
==============================

A library for convenient creation of Telegram bots by analogy with the creation of Web sites on Laravel.

v1.3.2(1w ago)0266MITPHPPHP ^8.3|^8.4|^8.5

Since Jul 23Pushed 1w agoCompare

[ Source](https://github.com/it-healer/laravel-telegram-bot)[ Packagist](https://packagist.org/packages/it-healer/laravel-telegram-bot)[ Docs](https://github.com/it-healer/laravel-telegram-bot)[ RSS](/packages/it-healer-laravel-telegram-bot/feed)WikiDiscussions main Synced today

READMEChangelog (8)Dependencies (22)Versions (14)Used By (0)

Laravel Telegram Bot
====================

[](#laravel-telegram-bot)

[![Latest Version on Packagist](https://camo.githubusercontent.com/43727f4817752f1bde2a5e4d69877a91a68107147d04b397cc09335f36ccd2b0/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f69742d6865616c65722f6c61726176656c2d74656c656772616d2d626f742e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/it-healer/laravel-telegram-bot)[![Total Downloads](https://camo.githubusercontent.com/f931651980033b155f8cb541b1f30f06142e2ef1d41d39f43c6d583d5dcb28b4/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f69742d6865616c65722f6c61726176656c2d74656c656772616d2d626f742e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/it-healer/laravel-telegram-bot)

This package for Laravel 11+ allows you to easily create interactive Telegram bots, using Laravel routing, and using Blade templates to conduct a dialogue with the user.

Supports Laravel 11, 12 and 13, PHP 8.3, 8.4 and 8.5.

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

[](#installation)

You can install the package via composer:

```
composer require it-healer/laravel-telegram-bot
```

```
php artisan telegram:install
```

You can publish and run the migrations with:

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

You can publish the config file with:

```
php artisan vendor:publish --tag="telegram-config"
```

Optionally, you can publish the views using:

```
php artisan vendor:publish --tag="telegram-views"
```

Optionally, if you use Sail for local development, you need add PHP params `PHP_CLI_SERVER_WORKERS="10"` in file `supervisord.conf`:

```
[program:php]
command=%(ENV_SUPERVISOR_PHP_COMMAND)s
user=%(ENV_SUPERVISOR_PHP_USER)s
environment=LARAVEL_SAIL="1",PHP_CLI_SERVER_WORKERS="10"
stdout_logfile=/dev/stdout
stdout_logfile_maxbytes=0
stderr_logfile=/dev/stderr
stderr_logfile_maxbytes=0
```

Authentication
--------------

[](#authentication)

You can use Laravel Auth, edit file `config/auth.php` and edit section `guards`:

```
'guards' => [
        'web' => [...],
        'telegram' => [
            'driver' => 'telegram',
            'provider' => 'users',
        ]
    ],
```

After this you can use middleware `auth:telegram` (and `guest:telegram`) in your routes.

The `telegram` guard is a stateful guard that links a Telegram chat to your authenticatable model through the `telegram_users` table. Use it like any other guard:

```
// Log in by credentials (any column except password, e.g. email or login):
Auth::guard('telegram')->attempt(['login' => $login, 'password' => $password]);

// Log in a known user instance:
Auth::guard('telegram')->login($user);

// Current user / logout:
Auth::guard('telegram')->user();
Auth::guard('telegram')->logout();
```

When `auth:telegram` blocks a guest, it redirects to the route named `telegram.user.auth`. When `guest:telegram` blocks an authenticated user, it redirects to the first existing route among `telegram.dashboard`, `telegram.home`, `telegram.index`.

Scheduling (optional)
---------------------

[](#scheduling-optional)

If you want to work with automatic truncate of dialogs, run the command `php artisan telegram:truncate` every minute using Schedule.

To live-refresh pages, register the `telegram.live` middleware alias:

```
->withMiddleware(function (Middleware $middleware) {
    $middleware->alias([
        'telegram.live' => \ItHealer\Telegram\Middleware\LiveMiddleware::class,
    ]);
})
```

Then use it in routes (the argument is the refresh frequency in seconds):

```
Route::telegram('/', [\App\Telegram\Controllers\MyController::class, 'index'])
    ->middleware(['telegram.live:30']);
```

In file `routes/console.php` add:

```
Schedule::command('telegram:live')->runInBackground()->everyMinute();
Schedule::command('telegram:truncate')->everyMinute();
```

Bot management commands
-----------------------

[](#bot-management-commands)

```
php artisan telegram:new-bot          # Register a new bot (asks for the token)
php artisan telegram:init             # Apply bot settings (name, description, commands) from config
php artisan telegram:set-webhook      # Set the webhook for a bot
php artisan telegram:unset-webhook    # Remove the webhook
php artisan telegram:pooling [BOT_ID] # Manual long-polling (useful on localhost)
php artisan telegram:truncate         # Clean up old dialog messages
php artisan telegram:live             # Process live-refreshing pages
```

Routing
-------

[](#routing)

Bot screens are defined in `routes/telegram.php` with the `Route::telegram()` macro. Routes are automatically named with a `telegram.` prefix.

```
use Illuminate\Support\Facades\Route;
use ItHealer\Telegram\TelegramRequest;

Route::telegram('/', function (TelegramRequest $request) {
    return 'You wrote: '.$request->text().'';
})->name('home');

Route::telegram('/profile', [\App\Telegram\Controllers\ProfileController::class, 'index'])
    ->name('profile')
    ->middleware('auth:telegram');
```

A handler may return a string of bot HTML, a `view(...)`, or a `redirect(...)` — redirects are followed internally and re-dispatched as another bot screen.

The `TelegramRequest` exposes the incoming update: `text()`, `post($key)`, `query()`, `chat()`, `user()`, etc.

Messages and formatting
-----------------------

[](#messages-and-formatting)

Bot output is written as HTML. The top-level tags are ``, media tags (see below), and ``.

```

    First line
    Bold, italic, underline, strike, code, link
    Multi-line / pre-formatted block kept as-is

```

- `` — a single line (newlines inside are stripped).
- `` — a block whose inner HTML is preserved as-is.
- Inside lines you can use Telegram HTML formatting tags (``, ``, ``, ``, ``, ``, ``, ``, …). Messages are sent with `parse_mode=html`.

### The `` tag

[](#the-screen-tag)

By default, messages are **appended** to the dialog ("classic" mode). When you wrap your output in ``, the bot **clears the current dialog and redraws everything inside from scratch** — useful for single-screen, app-like navigation where each step replaces the previous one.

```

        🏠 Main menu

                Profile

```

You can place several messages/media inside one ``. Mixing `` and top-level messages produces a "mixed" render (the screen part is redrawn, the rest is appended).

Media messages
--------------

[](#media-messages)

Send media by using a media tag with a `src` attribute (a local file path, a URL, or a Telegram `file_id`). Captions are written with ``/`` inside the tag.

```

    Caption with formatting

A file
A video

```

- `src` — local path, URL or `file_id`. Uploaded files are cached by content hash, so the same file is only uploaded once and reused by `file_id`.
- `show_caption_above_media="true"` — show the caption above the media.
- `reply-message-id="123"` — reply to a specific message (works on `` and media tags).

Inline keyboards
----------------

[](#inline-keyboards)

```

        Change a query param
        Send POST data

        Encoded POST data
        Redirect to a screen

        Open a URL
        Open a Web App

```

Supported `` attributes:

AttributeDescription`query-*`Set/override a query string parameter on the current screen.`data-*`Send POST data to the handler (`$request->post('field')`).`encode="true"`Encode long POST data via cache (default `true` when `data-redirect` is set).`data-redirect="/uri"`Navigate (redirect) to another screen.`data-current="field"`Edit-form: switch the current field (see Edit Form).`data-submit="true"`Edit-form: submit the form.`url="..."`Open an external URL.`web_app="..."`Open a Telegram Web App.`style="..."`Button color (Bot API 9.4+): `primary` (blue), `success` (green) or `danger` (red).`icon=""`Show a custom emoji on the button (`icon_custom_emoji_id`, Bot API 9.4+).### Colored buttons (button styles)

[](#colored-buttons-button-styles)

Since Bot API 9.4 you can color inline (and reply) keyboard buttons with the `style` attribute:

```

        🔑 Log in
        📝 Register

        🗑 Delete

```

Allowed values: `primary`, `success`, `danger`. Omit `style` for the default look. Old Telegram clients simply ignore the field. Invalid values throw an `InvalidArgumentException`.

You can do the same from PHP on the DTO:

```
use ItHealer\Telegram\DTO\InlineKeyboard\Button;

Button::make()
    ->setText('Delete')
    ->setCallbackData(['action' => 'delete'])
    ->setStyle('danger')
    ->setIconCustomEmojiId('5368324170671202286');
```

Reply keyboards
---------------

[](#reply-keyboards)

```

    Choose:

            Share contact
            Share location

            Web App
            Styled button

```

Supported `` attributes: `resize`, `persistent`. Supported `` attributes: `request_contact`, `request_location`, `web_app`, `style`, `icon`.

Edit Form
---------

[](#edit-form)

```
class MyForm extends \ItHealer\Telegram\EditForm\BaseForm
{
    public function rules(): array
    {
        return [
            'name' => ['required', 'string', 'min:5', 'max:255'],
            'phone' => ['required', 'string', 'min:10', 'max:15'],
        ];
    }

    public function titles(): array
    {
        return [
            'name' => 'Your name',
            'phone' => 'Your phone number'
        ];
    }
}
```

```
class MyController
{
    public function edit(MyForm $form): mixed
    {
        $form->setDefault([
            'name' => 'Default name',
            'phone' => '1234567890',
        ]);

        if( $form->validate() ) {
            // $form->get();
        }

        return view('...', compact('form'));
    }

    public function create(MyForm $form): mixed
    {
        if( $form->isCreate()->validate() ) {
            // $form->get();
        }

        return view('...', compact('form'));
    }
}
```

```

            Please, enter your First Name:

```

`isCreate()` walks through the fields one by one (asking each in turn) and returns `true` on submit; without it the form lets the user edit any field. Use `optional()` to allow empty values (the user can type `/empty`).

Sending and editing messages from code
--------------------------------------

[](#sending-and-editing-messages-from-code)

Use `ChatAPI` (e.g. via `$telegramChat->api()`):

```
$api = $chat->api();

$api->send($message);                 // send a Message DTO (text/photo/video/document/voice/...)
$api->edit($oldMessage, $newMessage); // edit an existing message
$api->delete($message);               // delete message(s)
$api->deleteMessages($id1, $id2);     // delete by message id(s)
$api->sendChatAction(ChatAction::Typing);
$api->getUserProfilePhotos();
```

The bot-level `API` (via `$bot->api()`) provides `getMe()` and `getFileLink($file)`.

Configuration
-------------

[](#configuration)

Key options in `config/telegram.php`:

- `reactions` — map incoming commands/emoji (e.g. `/start`, `🏠`, `/back`, `/refresh`) to navigation actions.
- `screen.ttl` / `screen.truncate` — lifetime of dialog messages and auto-truncate window.
- `page.timeout` / `page.wait` / `page.delay` / `page.max_redirects` — request handling tuning.
- `cache.ttl` / `cache.encode_ttl` — TTL for cached `file_id`s and encoded callback payloads.
- `models.bot` / `models.chat` / `models.user` — override the package's Eloquent models.
- `webhook.background` — handle webhook updates in the background.
- `init` — default bot name/description/commands applied by `telegram:init`.

Changelog
---------

[](#changelog)

Please see [CHANGELOG](CHANGELOG.md) for more information on what has changed recently.

Custom development &amp; contacts / Заказная разработка и контакты
------------------------------------------------------------------

[](#custom-development--contacts--заказная-разработка-и-контакты)

**EN** — Need a new project built from scratch, or this package integrated into your existing application? Contact the developer directly — custom development, module integration and ongoing support are available.

**RU** — Нужен новый проект «под ключ» или интеграция этого пакета в существующее приложение? Свяжитесь с разработчиком напрямую — доступны заказная разработка, интеграция модулей и поддержка.

- 🌐 Website / Сайт: [it-healer.com](https://it-healer.com)
- ✈️ Telegram: [@biodynamist](https://t.me/biodynamist) · +90 551 629 47 16
- 📱 WhatsApp: [+90 551 629 47 16](https://wa.me/905516294716)
- 📧 Email:
- 🐛 Issues / Баг-репорты: [GitHub Issues](https://github.com/it-healer/laravel-telegram-bot/issues)

Credits
-------

[](#credits)

- [IT-HEALER](https://github.com/it-healer)

License
-------

[](#license)

The MIT License (MIT). Please see [License File](LICENSE.md) for more information.

###  Health Score

48

↑

FairBetter than 93% of packages

Maintenance98

Actively maintained with recent releases

Popularity15

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity61

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

Recently: every ~2 days

Total

13

Last Release

8d ago

PHP version history (2 changes)v1.0.0PHP ^8.3|^8.4

v1.3.1PHP ^8.3|^8.4|^8.5

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/222434019?v=4)[IT-HEALER | Путь от Программиста к Целителю](/maintainers/it-healer)[@it-healer](https://github.com/it-healer)

---

Top Contributors

[![it-healer](https://avatars.githubusercontent.com/u/222434019?v=4)](https://github.com/it-healer "it-healer (13 commits)")

---

Tags

botlaravellibraryphptelegramtelegrambottgphplaraveltelegramlaravel-telegram-botit-healer

###  Code Quality

TestsPest

Code StyleLaravel Pint

### Embed Badge

![Health badge](/badges/it-healer-laravel-telegram-bot/health.svg)

```
[![Health](https://phpackages.com/badges/it-healer-laravel-telegram-bot/health.svg)](https://phpackages.com/packages/it-healer-laravel-telegram-bot)
```

###  Alternatives

[defstudio/telegraph

A laravel facade to interact with Telegram Bots

816333.8k3](/packages/defstudio-telegraph)[dedoc/scramble

Automatic generation of API documentation for Laravel applications.

2.1k11.2M100](/packages/dedoc-scramble)[psalm/plugin-laravel

Psalm plugin for Laravel

3355.3M346](/packages/psalm-plugin-laravel)[simplestats-io/laravel-client

Server-side analytics for Laravel that follows the full funnel from visit to registration to payment, attributed to the channel that drove it. Revenue, MRR, churn and ad-spend profit (ROAS/CAC) per channel. GDPR compliant, ad-blocker proof.

5021.9k](/packages/simplestats-io-laravel-client)[harris21/laravel-fuse

Circuit breaker for Laravel queue jobs. Protect your workers from cascading failures.

44855.7k](/packages/harris21-laravel-fuse)[laravel/ai

The official AI SDK for Laravel.

1.0k3.2M194](/packages/laravel-ai)

PHPackages © 2026

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