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

ActiveLibrary

phpsoftbox/telegram
===================

Telegram bot builder for the PhpSoftBox framework

049↓100%PHP

Since Mar 20Pushed 1mo agoCompare

[ Source](https://github.com/phpsoftbox/telegram)[ Packagist](https://packagist.org/packages/phpsoftbox/telegram)[ RSS](/packages/phpsoftbox-telegram/feed)WikiDiscussions master Synced 1mo ago

READMEChangelogDependenciesVersions (1)Used By (0)

Telegram
========

[](#telegram)

About
-----

[](#about)

`phpsoftbox/telegram` — компонент для построения Telegram-ботов: команды, обработчики, диалоги (Q&amp;A) и веб-хук.

Ключевые возможности:

- подключение к Telegram API и работа с webhook;
- роутинг команд и сообщений по типу;
- диалоги с вопросами, отменой и сбором данных;
- авторизация через Telegram Login Widget;
- очистка сообщений для «чистого экрана».

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

[](#quick-start)

Основная идея: `Bot` принимает update, сначала пытается продолжить активный диалог, затем отдает управление `UpdateRouter`.

```
use PhpSoftBox\Telegram\Api\TelegramClient;
use PhpSoftBox\Telegram\Bot\Bot;
use PhpSoftBox\Telegram\Conversation\ArrayConversationStore;
use PhpSoftBox\Telegram\Conversation\ConversationDefinition;
use PhpSoftBox\Telegram\Conversation\ConversationManager;
use PhpSoftBox\Telegram\Conversation\QuestionStep;
use PhpSoftBox\Telegram\Router\UpdateRouter;
use PhpSoftBox\Telegram\Webhook\WebhookHandler;

$client = new TelegramClient(
    token: $_ENV['TELEGRAM_BOT_TOKEN'],
    httpClient: $httpClient,
    requestFactory: $requestFactory,
    streamFactory: $streamFactory,
);

$router = new UpdateRouter();
$router->command('start', static function ($update, $context): void {
    $context->sendMessage($update->chatId(), 'Привет!');
});

$store = new ArrayConversationStore();
$conversations = new ConversationManager($store, $client);
$conversations->register(new ConversationDefinition('workspace.create', [
    new QuestionStep('name', 'Название воркспейса?'),
    new QuestionStep('description', 'Описание воркспейса?'),
]));

$router->command('workspace', static function ($update, $context) use ($conversations): void {
    $conversations->start('workspace.create', $update);
});

$bot = new Bot($client, $router, $conversations);
$handler = new WebhookHandler($bot, $responseFactory, $streamFactory);

$response = $handler->handle($request);
```

Команды и обработчики
---------------------

[](#команды-и-обработчики)

Команды и хендлеры регистрируются в `UpdateRouter`. Можно слушать текстовые сообщения, типы сообщений и fallback.

```
use PhpSoftBox\Telegram\Update\MessageTypeEnum;

$router->command('start', fn ($update, $context) => ...);
$router->onText(fn ($update, $context) => ...);
$router->onType(MessageTypeEnum::PHOTO, fn ($update, $context) => ...);
$router->fallback(fn ($update, $context) => ...);
```

Конфигурация бота
-----------------

[](#конфигурация-бота)

Если команд много, используйте `TelegramBotBuilder` и описывайте команды по файлам в `config/telegram` или через атрибуты.

```
use PhpSoftBox\Telegram\Builder\TelegramBotBuilder;

return static function (TelegramBotBuilder $bot): void {
    $bot->command('start', StartCommand::class);
    $bot->command('reset', ResetCommand::class);
};
```

### Несколько ботов

[](#несколько-ботов)

Можно держать несколько ботов, разделяя их по имени в конфиге (`auth`, `main`, `news`) и указывая `default`.

Диалоги (Q&amp;A)
-----------------

[](#диалоги-qa)

Диалоги строятся из последовательности шагов. Шаг может парсить и валидировать ответ пользователя.

```
$definition = new ConversationDefinition('workspace.edit', [
    new QuestionStep('name', 'Новое название?'),
    new QuestionStep('description', 'Новое описание?'),
]);
$definition = $definition->withCancelKeywords(['/cancel', 'cancel']);

$conversations->register($definition);
$conversations->start('workspace.edit', $update);
```

Авторизация через Telegram
--------------------------

[](#авторизация-через-telegram)

Авторизация вынесена в отдельный пакет `phpsoftbox/telegram-auth`.

Файлы
-----

[](#файлы)

Если в update приходит `file_id` (фото, видео, документ), файл можно скачать через `downloadFile`:

```
$fileId = $update->message()?->value();
if ($fileId !== null) {
    $client->downloadFile($fileId, __DIR__ . '/storage/file.bin');
}
```

Оглавление
----------

[](#оглавление)

- [Документация](docs/index.md)
- [CLI (long polling)](docs/07-cli.md)

Дополнения
----------

[](#дополнения)

- `phpsoftbox/telegram-auth` — авторизация через Telegram Login Widget.
- `phpsoftbox/telegram-mongo` — MongoDB-хранилище диалогов.

###  Health Score

23

—

LowBetter than 27% of packages

Maintenance63

Regular maintenance activity

Popularity11

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity11

Early-stage or recently created project

 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.

### Community

Maintainers

![](https://www.gravatar.com/avatar/0279d150240c97d210034878b0467462246dc14d29b5618157ff6a8be49a50e3?d=identicon)[inspector-who](/maintainers/inspector-who)

---

Top Contributors

[![inspector-who](https://avatars.githubusercontent.com/u/6973963?v=4)](https://github.com/inspector-who "inspector-who (1 commits)")

### Embed Badge

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

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

PHPackages © 2026

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