Compare commits

..

39 Commits

Author SHA1 Message Date
Alex 94ec907506 Added resumable upload tests 2025-08-27 21:26:33 +03:00
Alex 869c254275 Merge pull request #6 from BushlanovDev/resumable-upload
Resumable file upload
2025-08-26 21:10:53 +03:00
Alex cb8ad3f738 Added resumable upload tests 2025-08-26 21:08:07 +03:00
Alex 0f007bf94e Added resumable upload tests 2025-08-26 20:55:45 +03:00
Alex 3127f86c54 Added resumable upload 2025-08-25 23:11:06 +03:00
Alex ed715af3bc Update badger 2025-08-24 20:37:19 +03:00
Alex 008d6f4e0e Documentation 2025-08-22 20:17:28 +03:00
Alex 4784fcc97b Merge pull request #5 from BushlanovDev/fix-upload-files
Fix upload files
2025-08-21 19:31:21 +03:00
Alex d2aedc090f Documentation 2025-08-21 19:24:38 +03:00
Alex 92c8f4cd94 Fix upload files 2025-08-20 23:22:18 +03:00
Alex fa7875a670 Documentation 2025-08-19 21:26:05 +03:00
Alex 70c290ce0a Documentation 2025-08-18 21:29:43 +03:00
Alex de3a67bee7 Documentation & rename deleteAdmins to deleteAdmin 2025-08-17 22:40:21 +03:00
Alex b58dc8b2ed Documentation 2025-08-16 21:07:17 +03:00
Alex 00da3af39d Documentation and some fix 2025-08-15 20:17:30 +03:00
Alex ea1947239e Added badge laravel support 2025-08-14 14:34:40 +03:00
Alex 0bb13b3a7c release 1.0.0 2025-08-13 22:00:54 +03:00
Alex 17acd6de67 Laravel support tests 2025-08-12 22:18:20 +03:00
Alex b37e7b6a73 Laravel support tests 2025-08-11 20:48:04 +03:00
Alex 3b242c1186 Laravel support 2025-08-10 15:55:15 +03:00
Alex 59a843609b Merge pull request #3 from BushlanovDev/dev
Refactoring update dispatchers 
Added onCommand method
Added LongPollingHandler
2025-08-09 19:08:00 +03:00
Alex 9d56be2c92 Refactoring LongPollingHandler 2025-08-09 18:28:24 +03:00
Alex 9cd5dd2c48 Refactoring update dispatchers 2025-08-08 22:51:35 +03:00
Alex 1b00bae23a Some fix 2025-08-07 22:19:10 +03:00
Alex ca13096ec2 Added PSR LoggerInterface 2025-08-07 19:04:07 +03:00
Alex 68da594f89 Added OpenAppButton factory method 2025-08-06 20:52:37 +03:00
Alex 62fbb6cf3b Merge remote-tracking branch 'origin/master' 2025-08-05 18:15:48 +03:00
Alex 97d016055f fix #2 Error: Cannot instantiate abstract class AbstractAttachment после отправки номера телефона 2025-08-05 18:15:34 +03:00
Alex 13e7c3fa45 fix #1 Error: Cannot instantiate abstract class AbstractAttachment после отправки номера телефона 2025-08-05 18:11:34 +03:00
Alex 32e393e044 fix #1 TypeError Api::sendUserMessage после отправки сообщения
Added PhotoAttachmentRequestPayloadTest
2025-08-04 19:43:37 +03:00
Alex 728536f064 Added MessageStat & Attachments 2025-08-04 18:48:51 +03:00
Alex c5d55a5c0f Added DataAttachment & LinkedMessage & Markups 2025-08-03 15:07:05 +03:00
Alex 51b105b847 Added ChatButton & ReplyButtons 2025-08-02 09:24:11 +03:00
Alex f5acd0ee88 Added editBotInfo & editChat & getVideoAttachmentDetails 2025-08-01 08:42:39 +03:00
Alex 8fa63fa10b Added addAdmins & addMembers & editMessage & answerOnCallback 2025-07-31 09:31:33 +03:00
Alex eb5f6c7bbe Test fix 2025-07-30 09:00:24 +03:00
Alex 3810f340e9 Added getAdmins & deleteAdmins & getMembers & removeMember 2025-07-30 08:51:31 +03:00
Alex 46e7c2ef0a Added pinMessage & getMessages & deleteMessage & getMessageById 2025-07-29 19:09:33 +03:00
Alex a3dd4d9a29 Added getPinnedMessage & unpinMessage & getMembership & leaveChat 2025-07-28 18:57:27 +03:00
165 changed files with 13084 additions and 1405 deletions
+4 -5
View File
@@ -1,5 +1,4 @@
/.gitattributes export-ignore
/.gitignore export-ignore
/.github export-ignore
/phpunit.xml export-ignore
/tests export-ignore
/.* export-ignore
/phpunit.xml export-ignore
/phpstan.neon export-ignore
/tests export-ignore
@@ -5,7 +5,7 @@
<stop offset="1" stop-opacity=".1"/>
</linearGradient>
<mask id="a">
<rect width="99" height="20" rx="3" fill="#fff"/>
<rect width="99" height="20" fill="#fff"/>
</mask>
<g mask="url(#a)">
<path fill="#555" d="M0 0h63v20H0z"/>

Before

Width:  |  Height:  |  Size: 902 B

After

Width:  |  Height:  |  Size: 895 B

+141 -38
View File
@@ -1,74 +1,177 @@
# Max Bot API Client library for PHP
# Max Messenger Bot API Client library for PHP
[![Actions status](https://github.com/BushlanovDev/max-bot-api-client-php/actions/workflows/ci.yml/badge.svg?style=flat-square)](https://github.com/BushlanovDev/max-bot-api-client-php/actions)
[![Coverage](https://raw.githubusercontent.com/BushlanovDev/max-bot-api-client-php/refs/heads/master/badge-coverage.svg?v=1)](https://github.com/BushlanovDev/max-bot-api-client-php/actions)
[![Coverage](https://raw.githubusercontent.com/BushlanovDev/max-bot-api-client-php/refs/heads/master/.github/badge-coverage.svg?v=2)](https://github.com/BushlanovDev/max-bot-api-client-php/actions)
[![Packagist Version](https://img.shields.io/packagist/v/bushlanov-dev/max-bot-api-client-php.svg?style=flat-square)](https://packagist.org/packages/bushlanov-dev/max-bot-api-client-php)
[![PHP version](https://img.shields.io/badge/php-%3E%3D%208.3-8892BF.svg?style=flat-square)](https://github.com/BushlanovDev/max-bot-api-client-php)
[![Laravel](https://img.shields.io/badge/%20Laravel%20Package-available-success?logo=laravel&style=flat-square)](https://github.com/BushlanovDev/max-bot-api-client-php)
[![Software License](https://img.shields.io/badge/license-MIT-brightgreen.svg?style=flat-square)](LICENSE)
> [!CAUTION]
> На мой взгляд `Max Messenger` является ни чем иным как малварью, созданной для слежки за гражданами РФ. Настоятельно
> не рекомендую использовать его на реальных устройствах, с настоящим номером телефона, и для личной переписки.
> [!IMPORTANT]
> Библиотека в стадии активной разработки.
## Быстрый старт
> Если вы новичок, то можете прочитать [официальную документацию](https://dev.max.ru/), написанную разработчиками Max
> Если вы новичок, то можете прочитать [официальную документацию](https://dev.max.ru/), написанную разработчиками Max.
### Получение токена
Откройте диалог с [MasterBot](https://max.ru/MasterBot), следуйте инструкциям и создайте нового бота. После создания
бота MasterBot отправит вам токен.
### Установка библиотеки
```bash
composer require bushlanov-dev/max-bot-api-client-php
```
Пользователи Laravel могут зарегистрировать сервис провайдер и фасад в `config/app.php`:
```php
'providers' => [
// ...
BushlanovDev\MaxMessengerBot\Laravel\MaxBotServiceProvider::class,
],
// ...
'aliases' => [
// ...
'MaxBot' => BushlanovDev\MaxMessengerBot\Laravel\MaxBotFacade::class,
],
```
### Использование
Отправка сообщения с клавиатурой
```php
require __DIR__.'/vendor/autoload.php';
use BushlanovDev\MaxMessengerBot\Api;
$api = new Api('YOUR_BOT_API_TOKEN');
// Загрузка файла
$fileAttachmentRequest = $api->uploadAttachment(
type: UploadType::File,
filePath: __DIR__ . '/test.pdf',
);
$api->sendMessage(
userId: 123, // ID пользователя получателя сообщения
chatId: 321, // Или ID чата, в который нужно отправить сообщение
text: 'Привет!', // Текст сообщения, вы можете использовать HTML или Markdown
attachments: [
$fileAttachmentRequest,
new InlineKeyboardAttachmentRequest([
[new CallbackButton('Нажми меня!', 'payload_button1')],
[new LinkButton('Нажми меня!', 'https://example.com')],
]),
],
format: MessageFormat::Markdown, // Формат сообщения (Markdown или HTML)
);
```
Отправка сообщения с использованием фасада Laravel
```php
MaxBot::sendUserMessage(123456, 'Привет из Laravel!');
```
Создание универсального обработчика обновлений
```php
$dispatcher = $api->getUpdateDispatcher();
$dispatcher->onMessageCreated(function (MessageCreatedUpdate $update, Api $api) {
$api->sendMessage(
userId: $update->message->recipient->userId,
text: 'Привет!',
);
});
// или
$dispatcher->addHandler(UpdateType::BotStarted, function (BotStartedUpdate $update, Api $api) {
$api->sendMessage(
chatId: $update->chatId,
text: 'Я запущен!',
);
});
```
Подписка на вэб хуки
```php
$api->subscribe(
url: 'https://example.com/webhook', // URL на который будут приходить хуки
secret: 'super_secret', // Секретная фраза для проверки хуков
updateTypes: [
// Типы хуков которые вы хотите получать (либо ничего не указывать, чтобы получать все)
UpdateType::BotStarted,
UpdateType::MessageCreated,
],
);
```
Обработка обновлений
```php
$handler = $api->createWebhookHandler('super_secret'); // Обновления через вебхук
// ИЛИ
$handler = $api->createLongPollingHandler(); // Обновления через лонгполлинг
$handler->handle();
```
> ℹ️ С полной документацией [вы можете ознакомиться тут](./docs/README.md).
## Реализованные методы
#### Bots
- [x] `GET /me` (`getBotInfo`) *Получение информации о боте.*
- [ ] `PATCH /me` (`editBotInfo`) *Редактирование информации о боте.*
- [x] `GET /me` (`getBotInfo`) - [*Получение информации о боте.*](./docs/README.md#Получение-информации-о-боте)
- [x] `PATCH /me` (`editBotInfo`) - [*Редактирование информации о боте.*](./docs/README.md#Редактирование-информации-о-боте)
#### Chats
- [x] `GET /chats` (`getChats`) *Получение списка всех чатов бота.*
- [x] `GET /chats/{chatLink}` (`getChatByLink`) *Получение информации о чате по ссылке.*
- [x] `GET /chats/{chatId}` (`getChat`) *Получение информации о чате по ID.*
- [ ] `PATCH /chats/{chatId}` (`editChat`) *Редактирование информации о чате.*
- [x] `DELETE /chats/{chatId}` (`deleteChat`) *Удаление чата.*
- [x] `POST /chats/{chatId}/actions` (`sendAction`) *Отправка действия в чат (например, "печатает...").*
- [ ] `GET /chats/{chatId}/pin` (`getPinnedMessage`) *Получение закрепленного сообщения.*
- [ ] `PUT /chats/{chatId}/pin` (`pinMessage`) *Закрепление сообщения.*
- [ ] `DELETE /chats/{chatId}/pin` (`unpinMessage`) *Открепление сообщения.*
- [ ] `GET /chats/{chatId}/members/me` (`getMembership`) *Получение информации о членстве бота в чате.*
- [ ] `DELETE /chats/{chatId}/members/me` (`leaveChat`) *Выход бота из чата.*
- [ ] `GET /chats/{chatId}/members/admins` (`getAdmins`) *Получение администраторов чата.*
- [ ] `POST /chats/{chatId}/members/admins` (`postAdmins`) *Назначение администраторов чата.*
- [ ] `DELETE /chats/{chatId}/members/admins/{userId}` (`deleteAdmins`) *Снятие прав администратора.*
- [ ] `GET /chats/{chatId}/members` (`getMembers`) *Получение участников чата.*
- [ ] `POST /chats/{chatId}/members` (`addMembers`) *Добавление участников в чат.*
- [ ] `DELETE /chats/{chatId}/members` (`removeMember`) *Удаление участника из чата.*
- [x] `GET /chats` (`getChats`) - [*Получение списка всех чатов бота.*](./docs/README.md#Получение-списка-всех-чатов-бота)
- [x] `GET /chats/{chatLink}` (`getChatByLink`) - [*Получение информации о чате по ссылке.*](./docs/README.md#Получение-информации-о-чате-по-ссылке)
- [x] `GET /chats/{chatId}` (`getChat`) - [*Получение информации о чате по ID.*](./docs/README.md#Получение-информации-о-чате-по-ID)
- [x] `PATCH /chats/{chatId}` (`editChat`) - [*Редактирование информации о чате.*](./docs/README.md#Редактирование-информации-о-чате)
- [x] `DELETE /chats/{chatId}` (`deleteChat`) - [*Удаление чата.*](./docs/README.md#Удаление-чата)
- [x] `POST /chats/{chatId}/actions` (`sendAction`) - [*Отправка действия в чат (например, "печатает...").*](./docs/README.md#Отправка-действия-в-чат)
- [x] `GET /chats/{chatId}/pin` (`getPinnedMessage`) - [*Получение закрепленного сообщения.*](./docs/README.md#Получение-закрепленного-сообщения)
- [x] `PUT /chats/{chatId}/pin` (`pinMessage`) - [*Закрепление сообщения.*](./docs/README.md#Закрепление-сообщения)
- [x] `DELETE /chats/{chatId}/pin` (`unpinMessage`) - [*Открепление сообщения.*](./docs/README.md#Открепление-сообщения)
- [x] `GET /chats/{chatId}/members/me` (`getMembership`) - [*Получение информации о членстве бота в чате.*](./docs/README.md#Получение-информации-о-членстве-бота-в-чате)
- [x] `DELETE /chats/{chatId}/members/me` (`leaveChat`) - [*Выход бота из чата.*](./docs/README.md#Выход-бота-из-чата)
- [x] `GET /chats/{chatId}/members/admins` (`getAdmins`) - [*Получение администраторов чата.*](./docs/README.md#Получение-администраторов-чата)
- [x] `POST /chats/{chatId}/members/admins` (`addAdmins`) - [*Назначение администраторов чата.*](./docs/README.md#Назначение-администраторов-чата)
- [x] `DELETE /chats/{chatId}/members/admins/{userId}` (`deleteAdmin`) - [*Снятие прав администратора.*](./docs/README.md#Снятие-прав-администратора)
- [x] `GET /chats/{chatId}/members` (`getMembers`) - [*Получение участников чата.*](./docs/README.md#Получение-участников-чата)
- [x] `POST /chats/{chatId}/members` (`addMembers`) - [*Добавление участников в чат.*](./docs/README.md#Добавление-участников-в-чат)
- [x] `DELETE /chats/{chatId}/members` (`deleteMember`) - [*Удаление участника из чата.*](./docs/README.md#Удаление-участника-из-чата)
#### Subscriptions
- [x] `GET /subscriptions` (`getSubscriptions`) *Получение списка Webhook-подписок.*
- [x] `POST /subscriptions` (`subscribe`) *Создание Webhook-подписки.*
- [x] `DELETE /subscriptions` (`unsubscribe`) *Удаление Webhook-подписки.*
- [x] `GET /updates` (`getUpdates`) *Получение обновлений через Long-Polling.*
- [x] `GET /subscriptions` (`getSubscriptions`) - [*Получение списка Webhook-подписок.*](./docs/README.md#Получение-списка-Webhook-подписок)
- [x] `POST /subscriptions` (`subscribe`) - [*Создание Webhook-подписки.*](./docs/README.md#Создание-Webhook-подписки)
- [x] `DELETE /subscriptions` (`unsubscribe`) - [*Удаление Webhook-подписки.*](./docs/README.md#Удаление-Webhook-подписки)
- [x] `GET /updates` (`getUpdates`) - [*Получение обновлений через Long-Polling.*](./docs/README.md#Получение-обновлений-через-Long-Polling)
#### Upload
- [x] `POST /uploads` (`getUploadUrl`) *Получение URL для загрузки файла.*
- [x] `POST /uploads` (`getUploadUrl`) - [*Получение URL для загрузки файла.*](./docs/README.md#Получение-URL-для-загрузки-файла)
#### Messages
- [ ] `GET /messages` (`getMessages`) *Получение списка сообщений из чата.*
- [x] `POST /messages` (`sendMessage`) *Отправка сообщения.*
- [ ] `PUT /messages` (`editMessage`) *Редактирование сообщения.*
- [ ] `DELETE /messages` (`deleteMessage`) *Удаление сообщения.*
- [ ] `GET /messages/{messageId}` (`getMessageById`) *Получение сообщения по ID.*
- [ ] `GET /videos/{videoToken}` (`getVideoAttachmentDetails`) *Получение детальной информации о видео.*
- [ ] `POST /answers` (`answerOnCallback`) *Ответ на нажатие callback-кнопки.*
- [x] `GET /messages` (`getMessages`) - [*Получение списка сообщений из чата.*](./docs/README.md#Получение-списка-сообщений-из-чата)
- [x] `POST /messages` (`sendMessage`) - [*Отправка сообщения.*](./docs/README.md#Отправка-сообщения)
- [x] `PUT /messages` (`editMessage`) - [*Редактирование сообщения.*](./docs/README.md#Редактирование-сообщения)
- [x] `DELETE /messages` (`deleteMessage`) - [*Удаление сообщения.*](./docs/README.md#Удаление-сообщения)
- [x] `GET /messages/{messageId}` (`getMessageById`) - [*Получение сообщения по ID.*](./docs/README.md#Получение-сообщения-по-ID)
- [x] `GET /videos/{videoToken}` (`getVideoAttachmentDetails`) - [*Получение детальной информации о видео.*](./docs/README.md#Получение-детальной-информации-о-видео)
- [x] `POST /answers` (`answerOnCallback`) - [*Ответ на нажатие callback-кнопки.*](./docs/README.md#Ответ-на-нажатие-callback-кнопки)
## Лицензия
Данная библиотека распространяется по лицензии MIT - подробности см. в файле [LICENSE](LICENSE).
Данная библиотека распространяется под лицензией MIT - подробности см. в файле [LICENSE](LICENSE).
+21 -4
View File
@@ -1,7 +1,7 @@
{
"name": "bushlanov-dev/max-bot-api-client-php",
"description": "Max Bot API Client library",
"keywords": ["max messenger", "bot", "max", "api"],
"keywords": ["max messenger", "bot", "max", "api", "max bot", "laravel", "laravel max bot"],
"type": "library",
"license": "MIT",
"authors": [
@@ -19,12 +19,16 @@
"guzzlehttp/psr7": "^1.8||^2.0",
"psr/http-client": "^1.0",
"psr/http-factory": "^1.0",
"psr/http-message": "^1.0||^2.0"
"psr/http-message": "^1.0||^2.0",
"psr/log": "^3.0"
},
"require-dev": {
"friendsofphp/php-cs-fixer": "^3.77",
"jaschilz/php-coverage-badger": "^2.0",
"bushlanov-dev/php-coverage-badger": "^2.1",
"laravel/framework": "^11.0",
"mikey179/vfsstream": "^1.6",
"mockery/mockery": "^1.6",
"orchestra/testbench": "^9.0",
"php-mock/php-mock-phpunit": "^2.13",
"phpstan/phpstan": "^2.1",
"phpunit/phpunit": "^12.0",
@@ -43,11 +47,24 @@
"config": {
"sort-packages": true
},
"extra": {
"laravel": {
"providers": [
"BushlanovDev\\MaxMessengerBot\\Laravel\\MaxBotServiceProvider"
],
"aliases": {
"MaxBot": "BushlanovDev\\MaxMessengerBot\\Laravel\\MaxBotFacade"
}
}
},
"scripts": {
"analyse": "vendor/bin/phpstan analyse -c phpstan.neon --memory-limit=256M",
"format": "vendor/bin/php-cs-fixer fix --allow-risky=yes src",
"test": "vendor/bin/phpunit",
"test-coverage": "vendor/bin/phpunit --coverage-html coverage",
"create-coverage-badge": ["vendor/bin/phpunit --coverage-clover clover.xml", "vendor/bin/php-coverage-badger clover.xml badge-coverage.svg"]
"create-coverage-badge": [
"vendor/bin/phpunit --coverage-clover clover.xml",
"vendor/bin/php-coverage-badger --square clover.xml .github/badge-coverage.svg"
]
}
}
+446
View File
@@ -0,0 +1,446 @@
- [Быстрый старт](#Быстрый-старт)
- [Получение токена](#Получение-токена)
- [Установка библиотеки](#Установка-библиотеки)
- [Установка библиотеки в Laravel](#Установка-библиотеки-в-Laravel)
- [Инициализация бота](#Инициализация-бота)
- [Информация о боте](#Информация-о-боте)
- `GET /me` (`getBotInfo`) - [*Получение информации о боте.*](#Получение-информации-о-боте)
- `PATCH /me` (`editBotInfo`) - [*Редактирование информации о боте.*](#Редактирование-информации-о-боте)
- [Чаты](#Чаты)
- `GET /chats` (`getChats`) - [*Получение списка всех чатов бота.*](#Получение-списка-всех-чатов-бота)
- `GET /chats/{chatLink}` (`getChatByLink`) - [*Получение информации о чате по ссылке.*](#Получение-информации-о-чате-по-ссылке)
- `GET /chats/{chatId}` (`getChat`) - [*Получение информации о чате по ID.*](#Получение-информации-о-чате-по-ID)
- `PATCH /chats/{chatId}` (`editChat`) - [*Редактирование информации о чате.*](#Редактирование-информации-о-чате)
- `DELETE /chats/{chatId}` (`deleteChat`) - [*Удаление чата.*](#Удаление-чата)
- `POST /chats/{chatId}/actions` (`sendAction`) - [*Отправка действия в чат (например, "печатает...").*](#Отправка-действия-в-чат)
- `GET /chats/{chatId}/pin` (`getPinnedMessage`) - [*Получение закрепленного сообщения.*](#Получение-закрепленного-сообщения)
- `PUT /chats/{chatId}/pin` (`pinMessage`) - [*Закрепление сообщения.*](#Закрепление-сообщения)
- `DELETE /chats/{chatId}/pin` (`unpinMessage`) - [*Открепление сообщения.*](#Открепление-сообщения)
- `GET /chats/{chatId}/members/me` (`getMembership`) - [*Получение информации о членстве бота в чате.*](#Получение-информации-о-членстве-бота-в-чате)
- `DELETE /chats/{chatId}/members/me` (`leaveChat`) - [*Выход бота из чата.*](#Выход-бота-из-чата)
- `GET /chats/{chatId}/members/admins` (`getAdmins`) - [*Получение администраторов чата.*](#Получение-администраторов-чата)
- `POST /chats/{chatId}/members/admins` (`addAdmin`) - [*Назначение администраторов чата.*](#Назначение-администраторов-чата)
- `DELETE /chats/{chatId}/members/admins/{userId}` (`deleteAdmins`) - [*Снятие прав администратора.*](#Снятие-прав-администратора)
- `GET /chats/{chatId}/members` (`getMembers`) - [*Получение участников чата.*](#Получение-участников-чата)
- `POST /chats/{chatId}/members` (`addMembers`) - [*Добавление участников в чат.*](#Добавление-участников-в-чат)
- `DELETE /chats/{chatId}/members` (`deleteMember`) -[*Удаление участника из чата.*](#Удаление-участника-из-чата)
- [Получение обновлений](#Получение-обновлений)
- `GET /subscriptions` (`getSubscriptions`) - [*Получение списка Webhook-подписок.*](#Получение-списка-Webhook-подписок)
- `POST /subscriptions` (`subscribe`) - [*Создание Webhook-подписки.*](#Создание-Webhook-подписки)
- `DELETE /subscriptions` (`unsubscribe`) - [*Удаление Webhook-подписки.*](#Удаление-Webhook-подписки)
- `GET /updates` (`getUpdates`) - [*Получение обновлений через Long-Polling.*](#Получение-обновлений-через-Long-Polling)
- [Загрузка файлов](#Загрузка-файлов)
- `POST /uploads` (`getUploadUrl`) - [*Получение URL для загрузки файла.*](#Получение-URL-для-загрузки-файла)
- `uploadAttachment` - [*Загрузка файла.*](#Загрузка-файла)
- [Сообщения](#Сообщения)
- `GET /messages` (`getMessages`) - [*Получение списка сообщений из чата.*](#Получение-списка-сообщений-из-чата)
- `POST /messages` (`sendMessage`) - [*Отправка сообщения.*](#Отправка-сообщения)
- `PUT /messages` (`editMessage`) - [*Редактирование сообщения.*](#Редактирование-сообщения)
- `DELETE /messages` (`deleteMessage`) - [*Удаление сообщения.*](#Удаление-сообщения)
- `GET /messages/{messageId}` (`getMessageById`) - [*Получение сообщения по ID.*](#Получение-сообщения-по-ID)
- `GET /videos/{videoToken}` (`getVideoAttachmentDetails`) - [*Получение детальной информации о видео.*](#Получение-детальной-информации-о-видео)
- `POST /answers` (`answerOnCallback`) - [*Ответ на нажатие callback-кнопки.*](#Ответ-на-нажатие-callback-кнопки)
## Быстрый старт
> Если вы новичок, то можете прочитать [официальную документацию](https://dev.max.ru/), написанную разработчиками Max.
### Получение токена
Откройте диалог с [MasterBot](https://max.ru/MasterBot), следуйте инструкциям и создайте нового бота. После создания
бота MasterBot отправит вам токен.
### Установка библиотеки
```bash
composer require bushlanov-dev/max-bot-api-client-php
```
### Установка библиотеки в Laravel
Пользователи Laravel могут зарегистрировать сервис провайдер и фасад в `config/app.php`:
```php
'providers' => [
// ...
BushlanovDev\MaxMessengerBot\Laravel\MaxBotServiceProvider::class,
],
// ...
'aliases' => [
// ...
'MaxBot' => BushlanovDev\MaxMessengerBot\Laravel\MaxBotFacade::class,
],
```
При не необходимости опубликовать конфиг выполните следующую команду
```bash
php artisan vendor:publish --provider="BushlanovDev\MaxMessengerBot\Laravel\MaxBotServiceProvider"
```
Для работы вам потребуется внести следующие настройки в `.env`
```env
MAXBOT_ACCESS_TOKEN=your_bot_access_token_here
MAXBOT_WEBHOOK_SECRET=your_webhook_secret_here
MAXBOT_LOGGING_ENABLED=true
```
### Инициализация бота
Единственной обязательной настройкой является токен вашего бота.
⚠️ Никогда, и ни при каких обстоятельствах не храните токен в коде. ⚠️
Используйте переменные окружения!
```php
require __DIR__.'/vendor/autoload.php';
use BushlanovDev\MaxMessengerBot\Api;
$api = new Api('YOUR_BOT_API_TOKEN');
```
Так же вы можете создать экземпляр бота гибко настроив все зависимости под свои нужды.
```php
$api = new Api(
client: new Client(...),
modelFactory: new ModelFactory(),
logger: new YourPsrLogger(),
);
```
## Информация о боте
### Получение информации о боте
Возвращает информацию о текущем боте, который идентифицируется с помощью токена доступа.
Метод возвращает ID бота, его имя и аватар (если есть).
```php
$botInfo = $api->getBotInfo();
```
### Редактирование информации о боте
Обратите внимание, что данный метод отправляется PATCH запросом. Это значит, что будут обновлены только переданные
поля.
В следующем примере мы изменяем только название бота и отчистим его описание. Остальные поля останутся неизменными.
```php
$botInfo = $api->editBotInfo(
new BotPatch(
name: 'Супер бот',
description: null,
)
);
```
## Чаты
### Получение списка всех чатов бота
Возвращает информацию о чатах, в которых участвовал бот.
Результат включает список чатов и маркер для перехода к следующей странице.
```php
$chats = $api->getChats(
count: 10, // Количество запрашиваемых чатов
marker: 2, // Указатель на следующую страницу данных. Для первой страницы передайте null
);
```
### Получение информации о чате по ссылке
Возвращает информацию о чате по его публичной ссылке, либо информацию о диалоге с пользователем по его username.
```php
$chat = $api->getChatByLink('@super_chat'); // Публичная ссылка на чат или username пользователя
```
### Получение информации о чате по ID
```php
$chat = $api->getChat(12345);
```
### Редактирование информации о чате
Позволяет редактировать информацию о чате, включая название, иконку и закреплённое сообщение.
```php
$chat = $api->editChat(
chatId: 12345,
chatPatch: new ChatPatch(
title: 'Новое название чата',
),
);
```
### Удаление чата
```php
$api->deleteChat(12345);
```
### Отправка действия в чат
Позволяет отправлять действия бота в чат, такие как «набор текста» или «отправка фото».
```php
$api->sendAction(
chatId: 12345,
action: SenderAction::SendingVideo,
);
```
### Получение закрепленного сообщения
```php
$message = $api->getPinnedMessage(12345);
```
### Закрепление сообщения
```php
$api->pinMessage(
chatId: 12345,
messageId: 54321,
notify: true,
);
```
### Открепление сообщения
```php
$api->unpinMessage(12345);
```
### Получение информации о членстве бота в чате
```php
$chatMember = $api->getMembership(12345);
```
### Выход бота из чата
```php
$api->leaveChat(12345);
```
### Получение администраторов чата
Возвращает всех администраторов чата. Бот должен быть администратором в запрашиваемом чате.
```php
$adminsChatMemberList = $api->getAdmins(12345);
```
### Назначение администраторов чата
```php
$api->addAdmins(
chatId: 12345,
admins: [
new ChatAdmin(123, [ChatAdminPermission::ReadAllMessages]),
new ChatAdmin(456, [ChatAdminPermission::Write]),
],
);
```
### Снятие прав администратора
```php
$api->deleteAdmin(
chatId: 12345,
userId: 123,
);
```
### Получение участников чата
```php
$chatMemberList = $api->getMembers(12345);
```
### Добавление участников в чат
```php
$api->addMembers(
chatId: 12345,
userIds: [123, 456],
);
```
### Удаление участника из чата
```php
$api->deleteMember(
chatId: 12345,
userId: 123,
block: true, // Пользователь будет заблокирован в чате
);
```
## Получение обновлений
### Получение списка Webhook-подписок
```php
$subscriptions = $api->getSubscriptions();
```
### Создание Webhook-подписки
Подписывает бота на получение обновлений через WebHook.
После вызова этого метода бот будет получать уведомления о новых событиях в чатах на указанный URL.
Ваш сервер должен прослушивать один из следующих портов: 80, 8080, 443, 8443, 16384-32383.
```php
$api->subscribe(
url: 'https://example.com/webhook', // URL на который будут приходить хуки. Должен начинаться с http(s)://
secret: 'super_secret', // Секретная фраза для проверки хуков (необязательно)
updateTypes: [UpdateType::MessageCreated], // Типы хуков которые вы хотите получать (либо ничего не указывать, чтобы получать все)
);
```
### Удаление Webhook-подписки
```php
$api->unsubscribe('https://example.com/webhook');
```
### Получение обновлений через Long-Polling
Этот метод можно использовать для получения обновлений, если ваш бот не подписан на WebHook. Метод использует долгий опрос (long polling).
Каждое обновление имеет свой номер последовательности. Свойство marker в ответе указывает на следующее ожидаемое обновление.
Все предыдущие обновления считаются завершенными после прохождения параметра marker.
Если параметр marker не передан, бот получит все обновления, произошедшие после последнего подтверждения.
```php
$updateList = $api->getUpdates(
limit: 10, // Максимальное количество обновлений для получения [1-1000] (необязательно)
timeout: 10, // Таймаут в секундах [0-90] (необязательно)
marker: 123, // Если передан, бот получит обновления, которые еще не были получены (необязательно)
types: [UpdateType::MessageCreated], // Типы обновлений которые вы хотите получать (необязательно)
);
```
## Загрузка файлов
### Получение URL для загрузки файла
```php
$uploadEndpoint = $api->getUploadUrl(UploadType::Video);
// Далее вы можете загрузить файл по полученному URL самостоятельно
// или воспользоваться методами Client::multipartUpload(), Client::resumableUpload(), Api::uploadFile()
```
### Загрузка файла
Данный метод получит URL для загрузки, отправит файл и вернет готовый аттачмент
```php
$photoAttachmentRequest = $api->uploadAttachment(
type: UploadType::Image,
filePath: __DIR__ . '/test.jpg',
);
```
## Сообщения
### Получение списка сообщений из чата
Возвращает сообщения в чате: страницу с результатами и маркер, указывающий на следующую страницу.
Сообщения возвращаются в обратном порядке, то есть последние сообщения в чате будут первыми в массиве.
Поэтому, если вы используете параметры from и to, то to должно быть меньше, чем from.
```php
$messages = $api->getMessages(
chatId: 12345, // ID чата, чтобы получить сообщения из определённого чата (необязательно)
messageIds: [123, 456], // Список ID сообщений, которые нужно получить (необязательно)
from: 10, // Время начала для запрашиваемых сообщений [Unix timestamp] (необязательно)
to: 20, // Время окончания для запрашиваемых сообщений [Unix timestamp] (необязательно)
count: 10, // Максимальное количество сообщений в ответе [1-100] (необязательно)
);
```
### Отправка сообщения
```php
$fileAttachmentRequest = $api->uploadAttachment(
type: UploadType::File,
filePath: __DIR__ . '/test.pdf',
);
$message = $api->sendMessage(
userId: 12345, // Если вы отправляете сообщение пользователю, укажите его ID (необязательно)
chatId: 54321, // Если сообщение отправляется в чат, укажите его ID (необязательно)
text: 'Привет мир!', // Текст сообщения (необязательно)
attachments: [ // Прикрепленные элементы (необязательно)
$fileAttachmentRequest,
PhotoAttachmentRequest::fromUrl('https://example.com/image.jpg'),
new LocationAttachmentRequest(
latitude: 55.7520233,
longitude: 37.6174994,
),
],
format: MessageFormat::Markdown, // Формат сообщения Markdown или HTML (необязательно)
link: null, // Ссылка на сообщение (необязательно)
notify: true, // Если false, участники чата не будут уведомлены (необязательно)
disableLinkPreview: false, // Если false, сервер не будет генерировать превью для ссылок в тексте сообщения (необязательно)
);
```
### Редактирование сообщения
Редактирует сообщение в чате. Если поле attachments равно null, вложения текущего сообщения не изменяются.
Если в этом поле передан пустой список, все вложения будут удалены.
```php
$api->editMessage(
messageId: 12345,
text: 'Привет мир!',
attachments: null,
format: null,
link: null,
notify: true,
);
```
### Удаление сообщения
```php
$api->deleteMessage(12345);
```
### Получение сообщения по ID
```php
$message = $api->getMessageById(12345);
```
### Получение детальной информации о видео
Возвращает подробную информацию о приклеплённом видео. URL-адреса воспроизведения и дополнительные метаданные.
```php
$videoAttachmentDetails = $api->getVideoAttachmentDetails('some-video-token');
```
### Ответ на нажатие callback-кнопки
Этот метод используется для отправки ответа после того, как пользователь нажал на кнопку.
Ответом может быть обновленное сообщение и/или одноразовое уведомление для пользователя.
```php
$api->answerOnCallback(
callbackId: 'some-callback-id', // Идентификатор кнопки, по которой пользователь кликнул
notification: 'some-notification', // Заполните это, если хотите просто отправить одноразовое уведомление пользователю (необязательно)
text: 'some-text', // Новый текст сообщения (необязательно)
attachments: null, // Вложения сообщения. Если пусто, все вложения будут удалены (необязательно)
link: null, // Ссылка на сообщение (необязательно)
format: null, // Формат сообщения Markdown или HTML (необязательно)
notify: true, // Заполните это, если хотите просто отправить одноразовое уведомление пользователю (необязательно)
);
```
+3264
View File
File diff suppressed because it is too large Load Diff
+767 -140
View File
File diff suppressed because it is too large Load Diff
+88 -6
View File
@@ -19,6 +19,9 @@ use Psr\Http\Client\ClientInterface;
use Psr\Http\Message\RequestFactoryInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\StreamFactoryInterface;
use Psr\Log\LoggerInterface;
use Psr\Log\NullLogger;
use RuntimeException;
/**
* The low-level HTTP client responsible for communicating with the Max Bot API.
@@ -34,6 +37,7 @@ final readonly class Client implements ClientApiInterface
* @param StreamFactoryInterface $streamFactory A PSR-17 factory for creating request body streams.
* @param string $baseUrl The base URL for API requests.
* @param string|null $apiVersion The API version to use for requests.
* @param LoggerInterface $logger
*
* @throws InvalidArgumentException
*/
@@ -44,6 +48,7 @@ final readonly class Client implements ClientApiInterface
private StreamFactoryInterface $streamFactory,
private string $baseUrl,
private ?string $apiVersion = null,
private LoggerInterface $logger = new NullLogger(),
) {
if (empty($accessToken)) {
throw new InvalidArgumentException('Access token cannot be empty.');
@@ -60,6 +65,12 @@ final readonly class Client implements ClientApiInterface
$queryParams['v'] = $this->apiVersion;
}
$this->logger->debug('Sending API request', [
'method' => $method,
'url' => $this->baseUrl . $uri,
'body' => $body,
]);
$fullUrl = $this->baseUrl . $uri . '?' . http_build_query($queryParams);
$request = $this->requestFactory->createRequest($method, $fullUrl);
@@ -79,6 +90,10 @@ final readonly class Client implements ClientApiInterface
$response = $this->httpClient->sendRequest($request);
} catch (ClientExceptionInterface $e) {
// This catches network errors, DNS failures, timeouts, etc.
$this->logger->error('Network exception during API request', [
'message' => $e->getMessage(),
'exception' => $e,
]);
throw new NetworkException($e->getMessage(), $e->getCode(), $e);
}
@@ -86,6 +101,11 @@ final readonly class Client implements ClientApiInterface
$responseBody = (string)$response->getBody();
$this->logger->debug('Received API response', [
'status' => $response->getStatusCode(),
'body' => $responseBody,
]);
// Handle successful but empty responses (e.g., from DELETE endpoints)
if (empty($responseBody)) {
// The API spec often returns {"success": true}, so we can simulate that
@@ -103,7 +123,7 @@ final readonly class Client implements ClientApiInterface
/**
* @inheritDoc
*/
public function upload(string $uri, mixed $fileContents, string $fileName): array
public function multipartUpload(string $uri, mixed $fileContents, string $fileName): string
{
$boundary = '--------------------------' . microtime(true);
$bodyStream = $this->streamFactory->createStream();
@@ -133,13 +153,70 @@ final readonly class Client implements ClientApiInterface
$this->handleErrorResponse($response);
$responseBody = (string)$response->getBody();
return (string)$response->getBody();
}
try {
return json_decode($responseBody, true, 512, JSON_THROW_ON_ERROR);
} catch (JsonException $e) {
throw new SerializationException('Failed to decode upload server response JSON.', 0, $e);
/**
* @inheritDoc
*/
public function resumableUpload(
string $uploadUrl,
mixed $fileResource,
string $fileName,
int $fileSize,
int $chunkSize = 1048576,
): string {
if (!is_resource($fileResource) || get_resource_type($fileResource) !== 'stream') {
throw new InvalidArgumentException('fileResource must be a valid stream resource.');
}
// @phpstan-ignore-next-line
if ($fileSize <= 0) {
throw new InvalidArgumentException('File size must be greater than 0.');
}
$startByte = 0;
$finalResponseBody = '';
while (!feof($fileResource)) {
$chunk = fread($fileResource, $chunkSize);
if ($chunk === false) {
// @codeCoverageIgnoreStart
throw new RuntimeException('Failed to read chunk from file stream.');
// @codeCoverageIgnoreEnd
}
$chunkLength = strlen($chunk);
if ($chunkLength === 0) {
break;
}
$endByte = $startByte + $chunkLength - 1;
$chunkStream = $this->streamFactory->createStream($chunk);
$request = $this->requestFactory->createRequest('POST', $uploadUrl)
->withBody($chunkStream)
->withHeader('Content-Type', 'application/octet-stream')
->withHeader('Content-Disposition', 'attachment; filename="' . $fileName . '"')
->withHeader('Content-Range', "bytes {$startByte}-{$endByte}/{$fileSize}");
try {
$response = $this->httpClient->sendRequest($request);
} catch (ClientExceptionInterface $e) {
throw new NetworkException($e->getMessage(), $e->getCode(), $e);
}
$this->handleErrorResponse($response);
// The final response might contain the retval
$finalResponseBody = (string)$response->getBody();
$startByte += $chunkLength;
}
// According to docs, for video/audio the token is sent separately,
// and the upload response contains 'retval'. We return the body of the last response.
return $finalResponseBody;
}
/**
@@ -161,6 +238,11 @@ final readonly class Client implements ClientApiInterface
$errorCode = $data['code'] ?? 'unknown';
$errorMessage = $data['message'] ?? 'An unknown error occurred.';
$this->logger->error('API error response received', [
'status' => $statusCode,
'body' => $responseBody,
]);
throw match ($statusCode) {
401 => new UnauthorizedException($errorMessage, $errorCode, $response),
403 => new ForbiddenException($errorMessage, $errorCode, $response),
+27 -3
View File
@@ -7,6 +7,7 @@ namespace BushlanovDev\MaxMessengerBot;
use BushlanovDev\MaxMessengerBot\Exceptions\ClientApiException;
use BushlanovDev\MaxMessengerBot\Exceptions\NetworkException;
use BushlanovDev\MaxMessengerBot\Exceptions\SerializationException;
use RuntimeException;
interface ClientApiInterface
{
@@ -26,16 +27,39 @@ interface ClientApiInterface
public function request(string $method, string $uri, array $queryParams = [], array $body = []): array;
/**
* Performs a file download at the specified URL.
* Performs a file upload at the specified URL.
*
* @param string $uri URL received from the download API.
* @param resource|string $fileContents File content (stream resource or string).
* @param string $fileName The name of the file that will be sent to the server.
*
* @return array<string, mixed>
* @return string The raw response body from the upload server.
* @throws ClientApiException
* @throws NetworkException
* @throws SerializationException
*/
public function upload(string $uri, mixed $fileContents, string $fileName): array;
public function multipartUpload(string $uri, mixed $fileContents, string $fileName): string;
/**
* Uploads a file in chunks using the resumable upload method.
* The caller is responsible for opening and closing the file resource.
*
* @param string $uploadUrl The target URL for the upload.
* @param resource $fileResource A stream resource pointing to the file.
* @param string $fileName The desired file name for the upload.
* @param int<1, max> $fileSize The total size of the file in bytes.
* @param int<1, max> $chunkSize The size of each chunk in bytes.
*
* @return string The body of the final response from the server.
* @throws NetworkException
* @throws ClientApiException
* @throws RuntimeException
*/
public function resumableUpload(
string $uploadUrl,
$fileResource,
string $fileName,
int $fileSize,
int $chunkSize = 1048576,
): string;
}
+3 -1
View File
@@ -4,7 +4,7 @@ declare(strict_types=1);
namespace BushlanovDev\MaxMessengerBot\Enums;
enum AttachmentType: string
enum AttachmentType: string
{
case Image = 'image';
case Video = 'video';
@@ -13,6 +13,8 @@ enum AttachmentType: string
case Sticker = 'sticker';
case Contact = 'contact';
case InlineKeyboard = 'inline_keyboard';
case ReplyKeyboard = 'reply_keyboard';
case Location = 'location';
case Share = 'share';
case Data = 'data';
}
+18
View File
@@ -0,0 +1,18 @@
<?php
declare(strict_types=1);
namespace BushlanovDev\MaxMessengerBot\Enums;
/**
* Defines the permissions an administrator can have in a chat.
*/
enum ChatAdminPermission: string
{
case ReadAllMessages = 'read_all_messages';
case AddRemoveMembers = 'add_remove_members';
case AddAdmins = 'add_admins';
case ChangeChatInfo = 'change_chat_info';
case PinMessage = 'pin_message';
case Write = 'write';
}
@@ -4,7 +4,7 @@ declare(strict_types=1);
namespace BushlanovDev\MaxMessengerBot\Enums;
enum ButtonType: string
enum InlineButtonType: string
{
case Callback = 'callback';
case Link = 'link';
@@ -12,4 +12,5 @@ enum ButtonType: string
case RequestContact = 'request_contact';
case OpenApp = 'open_app';
case Message = 'message';
case Chat = 'chat';
}
+18
View File
@@ -0,0 +1,18 @@
<?php
declare(strict_types=1);
namespace BushlanovDev\MaxMessengerBot\Enums;
enum MarkupType: string
{
case Strong = 'strong';
case Emphasized = 'emphasized';
case Monospaced = 'monospaced';
case Link = 'link';
case Strikethrough = 'strikethrough';
case Underline = 'underline';
case UserMention = 'user_mention';
case Heading = 'heading';
case Highlighted = 'highlighted';
}
+12
View File
@@ -0,0 +1,12 @@
<?php
declare(strict_types=1);
namespace BushlanovDev\MaxMessengerBot\Enums;
enum ReplyButtonType: string
{
case Message = 'message';
case UserGeoLocation = 'user_geo_location';
case UserContact = 'user_contact';
}
-5
View File
@@ -5,12 +5,7 @@ declare(strict_types=1);
namespace BushlanovDev\MaxMessengerBot\Exceptions;
use RuntimeException;
use Throwable;
class NetworkException extends RuntimeException
{
public function __construct(string $message = "", int $code = 0, ?Throwable $previous = null)
{
parent::__construct($message, $code, $previous);
}
}
@@ -5,12 +5,7 @@ declare(strict_types=1);
namespace BushlanovDev\MaxMessengerBot\Exceptions;
use LogicException;
use Throwable;
class SerializationException extends LogicException
{
public function __construct(string $message = "", int $code = 0, ?Throwable $previous = null)
{
parent::__construct($message, $code, $previous);
}
}
@@ -0,0 +1,57 @@
<?php
declare(strict_types=1);
namespace BushlanovDev\MaxMessengerBot\Laravel\Commands;
use BushlanovDev\MaxMessengerBot\Laravel\MaxBotManager;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;
use Throwable;
/**
* Artisan command to start processing updates via long polling.
*/
class PollingStartCommand extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'maxbot:polling:start
{--timeout=90 : Timeout in seconds for long polling}';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Start the bot to process updates via long polling';
/**
* Execute the console command.
*/
public function handle(MaxBotManager $botManager): int
{
$timeout = (int)$this->option('timeout');
$this->info("Starting long polling with a timeout of $timeout seconds... Press Ctrl+C to stop.");
try {
$botManager->startLongPolling($timeout);
// @codeCoverageIgnoreStart
// This part is unreachable as startLongPolling is an infinite loop
return self::SUCCESS;
// @codeCoverageIgnoreEnd
} catch (Throwable $e) {
Log::error("Long polling failed to start or crashed: {$e->getMessage()}", [
'exception' => $e,
]);
$this->error("❌ Long polling failed: {$e->getMessage()}");
return self::FAILURE;
}
}
}
@@ -0,0 +1,74 @@
<?php
declare(strict_types=1);
namespace BushlanovDev\MaxMessengerBot\Laravel\Commands;
use BushlanovDev\MaxMessengerBot\Api;
use BushlanovDev\MaxMessengerBot\Enums\UpdateType;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;
use Throwable;
/**
* Artisan command for listing active webhook subscriptions.
*/
class WebhookListCommand extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'maxbot:webhook:list';
/**
* The console command description.
*
* @var string
*/
protected $description = 'List all active webhook subscriptions';
/**
* Execute the console command.
*/
public function handle(Api $api): int
{
$this->info('Fetching webhook subscriptions...');
try {
$subscriptions = $api->getSubscriptions();
if (empty($subscriptions)) {
$this->info('No active webhook subscriptions found.');
return self::SUCCESS;
}
$this->info('Found ' . count($subscriptions) . ' active webhook subscription(s):');
$this->newLine();
$headers = ['URL', 'Update Types', 'Created At'];
$rows = [];
foreach ($subscriptions as $subscription) {
$rows[] = [
$subscription->url,
implode(', ', $subscription->updateTypes ? array_map(fn (UpdateType $updateType) => $updateType->value, $subscription->updateTypes) : ['all']),
date('Y-m-d H:i:s', $subscription->time),
];
}
$this->table($headers, $rows);
return self::SUCCESS;
} catch (Throwable $e) {
Log::error("Webhook list error: {$e->getMessage()}", [
'exception' => $e,
]);
$this->error("❌ Webhook list error: {$e->getMessage()}");
return self::FAILURE;
}
}
}
@@ -0,0 +1,98 @@
<?php
declare(strict_types=1);
namespace BushlanovDev\MaxMessengerBot\Laravel\Commands;
use BushlanovDev\MaxMessengerBot\Api;
use BushlanovDev\MaxMessengerBot\Enums\UpdateType;
use Illuminate\Console\Command;
use Illuminate\Contracts\Config\Repository as Config;
use Illuminate\Support\Facades\Log;
use Throwable;
/**
* Artisan command for subscribing to webhook updates.
*/
class WebhookSubscribeCommand extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'maxbot:webhook:subscribe
{url : The webhook URL to subscribe to}
{--secret= : Secret key for webhook verification (optional)}
{--types=* : Update types to subscribe to (optional)}';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Subscribe bot to webhook updates';
/**
* Execute the console command.
*/
public function handle(Api $api, Config $config): int
{
$url = (string)$this->argument('url'); // @phpstan-ignore-line
$secret = $this->option('secret') ?? $config->get('maxbot.webhook_secret');
$types = $this->option('types');
if (!filter_var($url, FILTER_VALIDATE_URL)) {
$this->error('Invalid URL provided.');
return self::FAILURE;
}
$updateTypes = null;
if (is_array($types) && !empty($types)) {
$updateTypes = [];
foreach ($types as $type) {
try {
$updateTypes[] = UpdateType::from($type);
} catch (\ValueError $e) {
$this->error("Invalid update type: $type");
return self::FAILURE;
}
}
}
$this->info('Subscribing to webhook...');
$this->line("URL: $url");
if ($secret) {
$this->line("Secret: " . str_repeat('*', strlen($secret)));
}
if ($updateTypes) {
$this->line("Update types: " . implode(', ', array_map(fn($type) => $type->value, $updateTypes)));
} else {
$this->line("Update types: All (default)");
}
try {
$result = $api->subscribe($url, $secret, $updateTypes);
if ($result->success) {
$this->info('✅ Successfully subscribed to webhook!');
return self::SUCCESS;
} else {
$this->error('❌ Failed to subscribe to webhook.');
$this->line("Response: $result->message");
return self::FAILURE;
}
} catch (Throwable $e) {
Log::error("Webhook subscription error: {$e->getMessage()}", [
'exception' => $e,
]);
$this->error("❌ Webhook subscription error: {$e->getMessage()}");
return self::FAILURE;
}
}
}
@@ -0,0 +1,80 @@
<?php
declare(strict_types=1);
namespace BushlanovDev\MaxMessengerBot\Laravel\Commands;
use BushlanovDev\MaxMessengerBot\Api;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;
use Throwable;
/**
* Artisan command for unsubscribing from webhook updates.
*/
class WebhookUnsubscribeCommand extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'maxbot:webhook:unsubscribe
{url : The webhook URL to unsubscribe from}
{--confirm : Skip confirmation prompt}';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Unsubscribe bot from webhook updates';
/**
* Execute the console command.
*/
public function handle(Api $api): int
{
$url = (string)$this->argument('url'); // @phpstan-ignore-line
$confirm = $this->option('confirm');
if (!filter_var($url, FILTER_VALIDATE_URL)) {
$this->error('Invalid URL provided.');
return self::FAILURE;
}
if (!$confirm) {
if (!$this->confirm("Are you sure you want to unsubscribe from webhook URL: $url?")) {
$this->info('Operation cancelled.');
return self::SUCCESS;
}
}
$this->info('Unsubscribing from webhook...');
$this->line("URL: $url");
try {
$result = $api->unsubscribe($url);
if ($result->success) {
$this->info('✅ Successfully unsubscribed from webhook!');
return self::SUCCESS;
} else {
$this->error('❌ Failed to unsubscribe from webhook.');
$this->line("Response: $result->message");
return self::FAILURE;
}
} catch (Throwable $e) {
Log::error("Webhook unsubscribe error: {$e->getMessage()}", [
'exception' => $e,
]);
$this->error("❌ Webhook unsubscribe error: {$e->getMessage()}");
return self::FAILURE;
}
}
}
+91
View File
@@ -0,0 +1,91 @@
<?php
declare(strict_types=1);
namespace BushlanovDev\MaxMessengerBot\Laravel;
use BushlanovDev\MaxMessengerBot\Api;
use BushlanovDev\MaxMessengerBot\Enums\MessageFormat;
use BushlanovDev\MaxMessengerBot\Enums\SenderAction;
use BushlanovDev\MaxMessengerBot\Enums\UpdateType;
use BushlanovDev\MaxMessengerBot\Enums\UploadType;
use BushlanovDev\MaxMessengerBot\Models\Attachments\Requests\AbstractAttachmentRequest;
use BushlanovDev\MaxMessengerBot\Models\BotInfo;
use BushlanovDev\MaxMessengerBot\Models\BotPatch;
use BushlanovDev\MaxMessengerBot\Models\Chat;
use BushlanovDev\MaxMessengerBot\Models\ChatAdmin;
use BushlanovDev\MaxMessengerBot\Models\ChatList;
use BushlanovDev\MaxMessengerBot\Models\ChatMember;
use BushlanovDev\MaxMessengerBot\Models\ChatMembersList;
use BushlanovDev\MaxMessengerBot\Models\ChatPatch;
use BushlanovDev\MaxMessengerBot\Models\Message;
use BushlanovDev\MaxMessengerBot\Models\MessageLink;
use BushlanovDev\MaxMessengerBot\Models\Result;
use BushlanovDev\MaxMessengerBot\Models\Subscription;
use BushlanovDev\MaxMessengerBot\Models\UpdateList;
use BushlanovDev\MaxMessengerBot\Models\UploadEndpoint;
use BushlanovDev\MaxMessengerBot\Models\VideoAttachmentDetails;
use BushlanovDev\MaxMessengerBot\UpdateDispatcher;
use BushlanovDev\MaxMessengerBot\WebhookHandler;
use BushlanovDev\MaxMessengerBot\LongPollingHandler;
use Illuminate\Support\Facades\Facade;
/**
* Laravel Facade for Max Bot API Client.
*
* Provides static access to the Max Bot API methods through Laravel's facade system.
*
* @method static array<string, mixed> request(string $method, string $uri, array<string, mixed> $queryParams = [], array<string, mixed> $body = [])
* @method static UpdateDispatcher getUpdateDispatcher()
* @method static WebhookHandler createWebhookHandler(?string $secret = null)
* @method static LongPollingHandler createLongPollingHandler()
* @method static UpdateList getUpdates(?int $limit = null, ?int $timeout = null, ?int $marker = null, ?array<UpdateType> $types = null)
* @method static BotInfo getBotInfo()
* @method static Subscription[] getSubscriptions()
* @method static Result subscribe(string $url, ?string $secret = null, ?array<UpdateType> $updateTypes = null)
* @method static Result unsubscribe(string $url)
* @method static Message sendMessage(?int $userId = null, ?int $chatId = null, ?string $text = null, ?array<AbstractAttachmentRequest> $attachments = null, ?MessageFormat $format = null, ?MessageLink $link = null, bool $notify = true, bool $disableLinkPreview = false)
* @method static Message sendUserMessage(?int $userId = null, ?string $text = null, ?array<AbstractAttachmentRequest> $attachments = null, ?MessageFormat $format = null, ?MessageLink $link = null, bool $notify = true, bool $disableLinkPreview = false)
* @method static Message sendChatMessage(?int $chatId = null, ?string $text = null, ?array<AbstractAttachmentRequest> $attachments = null, ?MessageFormat $format = null, ?MessageLink $link = null, bool $notify = true, bool $disableLinkPreview = false)
* @method static UploadEndpoint getUploadUrl(UploadType $type)
* @method static AbstractAttachmentRequest uploadAttachment(UploadType $type, string $filePath)
* @method static Chat getChat(int $chatId)
* @method static Chat getChatByLink(string $chatLink)
* @method static ChatList getChats(?int $count = null, ?int $marker = null)
* @method static Result deleteChat(int $chatId)
* @method static Result sendAction(int $chatId, SenderAction $action)
* @method static Message|null getPinnedMessage(int $chatId)
* @method static Result unpinMessage(int $chatId)
* @method static ChatMember getMembership(int $chatId)
* @method static Result leaveChat(int $chatId)
* @method static Message[] getMessages(int $chatId, ?array<string> $messageIds = null, ?int $from = null, ?int $to = null, ?int $count = null)
* @method static Result deleteMessage(string $messageId)
* @method static Message getMessageById(string $messageId)
* @method static Result pinMessage(int $chatId, string $messageId, bool $notify = true)
* @method static ChatMembersList getAdmins(int $chatId)
* @method static ChatMembersList getMembers(int $chatId, ?array<int> $userIds = null, ?int $marker = null, ?int $count = null)
* @method static Result deleteAdmin(int $chatId, int $userId)
* @method static Result deleteMember(int $chatId, int $userId, bool $block = false)
* @method static Result addAdmins(int $chatId, array<ChatAdmin> $admins)
* @method static Result addMembers(int $chatId, array<int> $userIds)
* @method static Result answerOnCallback(string $callbackId, ?string $notification = null, ?string $text = null, ?array<AbstractAttachmentRequest> $attachments = null, ?MessageLink $link = null, ?MessageFormat $format = null, bool $notify = true)
* @method static Result editMessage(string $messageId, ?string $text = null, ?array<AbstractAttachmentRequest> $attachments = null, ?MessageFormat $format = null, ?MessageLink $link = null, bool $notify = true)
* @method static BotInfo editBotInfo(BotPatch $botPatch)
* @method static Chat editChat(int $chatId, ChatPatch $chatPatch)
* @method static VideoAttachmentDetails getVideoAttachmentDetails(string $videoToken)
*
* @see Api
* @codeCoverageIgnore
*/
class MaxBotFacade extends Facade
{
/**
* Get the registered name of the component.
*
* @return string
*/
protected static function getFacadeAccessor(): string
{
return 'maxbot';
}
}
+363
View File
@@ -0,0 +1,363 @@
<?php
declare(strict_types=1);
namespace BushlanovDev\MaxMessengerBot\Laravel;
use BushlanovDev\MaxMessengerBot\Api;
use BushlanovDev\MaxMessengerBot\Enums\UpdateType;
use BushlanovDev\MaxMessengerBot\Exceptions\SecurityException;
use BushlanovDev\MaxMessengerBot\Exceptions\SerializationException;
use BushlanovDev\MaxMessengerBot\Models\Updates\AbstractUpdate;
use BushlanovDev\MaxMessengerBot\UpdateDispatcher;
use BushlanovDev\MaxMessengerBot\WebhookHandler;
use BushlanovDev\MaxMessengerBot\LongPollingHandler;
use GuzzleHttp\Psr7\ServerRequest;
use Illuminate\Contracts\Container\BindingResolutionException;
use Illuminate\Contracts\Container\Container;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Log;
use Throwable;
/**
* Max Bot Manager for Laravel integration.
*
* Provides convenient methods for integrating Max Bot with Laravel applications.
* Handles webhook processing, long polling, and event dispatching within Laravel context.
*/
class MaxBotManager
{
/**
* @param Container $container
* @param Api $api
* @param UpdateDispatcher $dispatcher
*/
public function __construct(
private readonly Container $container,
private readonly Api $api,
private readonly UpdateDispatcher $dispatcher,
) {
}
/**
* Handle webhook request in Laravel controller.
*
* Example usage in a controller:
* ```php
* public function webhook(Request $request, MaxBotManager $botManager)
* {
* return $botManager->handleWebhook($request);
* }
* ```
*/
public function handleWebhook(Request $request): JsonResponse|Response
{
try {
/** @var WebhookHandler $webhookHandler */
$webhookHandler = $this->container->make(WebhookHandler::class);
$headers = array_map(function ($values) {
return array_filter($values, fn($value) => $value !== null);
}, $request->headers->all());
$webhookHandler->handle(
new ServerRequest(
$request->getMethod(),
$request->getUri(),
$headers,
$request->getContent(),
$request->getProtocolVersion() ?? '1.1',
)
);
return new Response('', 200);
} catch (SecurityException $e) {
Log::warning("Webhook security error: {$e->getMessage()}", [
'exception' => $e,
'headers' => $request->headers->all(),
]);
return new JsonResponse([
'status' => 'error',
'message' => 'Forbidden',
], 403);
} catch (SerializationException $e) {
Log::error("Webhook serialization error: {$e->getMessage()}", [
'exception' => $e,
'request_content' => $request->getContent(),
]);
return new JsonResponse([
'status' => 'error',
'message' => 'Bad Request',
], 400);
} catch (Throwable $e) {
Log::error("Webhook processing error: {$e->getMessage()}", [
'exception' => $e,
'request_content' => $request->getContent(),
'headers' => $request->headers->all(),
]);
return new JsonResponse([
'status' => 'error',
'message' => 'Internal Server Error',
], 500);
}
}
/**
* Start long polling in Laravel context.
* This method should be called from a Laravel command or job.
* It will run indefinitely until stopped.
*
* @throws BindingResolutionException
* @codeCoverageIgnore
*/
public function startLongPolling(int $timeout = 90, ?int $marker = null): void
{
/** @var LongPollingHandler $longPolling */
$longPolling = $this->container->make(LongPollingHandler::class);
$longPolling->handle($timeout, $marker);
}
/**
* Registers a handler for a specific update type.
*
* @param UpdateType $type The type of update to handle.
* @param callable|string $handler Can be a closure, callable, or Laravel container binding.
*
* @throws BindingResolutionException
* @codeCoverageIgnore
*/
public function addHandler(UpdateType $type, callable|string $handler): void
{
$this->dispatcher->addHandler($type, $this->resolveHandler($handler));
}
/**
* Register a command handler.
*
* @param string $command Command name (without slash)
* @param callable|string $handler Can be a closure, callable, or Laravel container binding.
*
* @throws BindingResolutionException
* @codeCoverageIgnore
*/
public function onCommand(string $command, callable|string $handler): void
{
$this->dispatcher->onCommand($command, $this->resolveHandler($handler));
}
/**
* Register a message created handler.
*
* @param callable|string $handler Can be a closure, callable, or Laravel container binding.
*
* @throws BindingResolutionException
* @codeCoverageIgnore
*/
public function onMessageCreated(callable|string $handler): void
{
$this->dispatcher->onMessageCreated($this->resolveHandler($handler));
}
/**
* Register a callback handler.
*
* @param callable|string $handler Can be a closure, callable, or Laravel container binding.
*
* @throws BindingResolutionException
* @codeCoverageIgnore
*/
public function onMessageCallback(callable|string $handler): void
{
$this->dispatcher->onMessageCallback($this->resolveHandler($handler));
}
/**
* Register a message edited handler.
*
* @param callable|string $handler Can be a closure, callable, or Laravel container binding.
*
* @throws BindingResolutionException
* @codeCoverageIgnore
*/
public function onMessageEdited(callable|string $handler): void
{
$this->dispatcher->onMessageEdited($this->resolveHandler($handler));
}
/**
* Register a message removed handler.
*
* @param callable|string $handler Can be a closure, callable, or Laravel container binding.
*
* @throws BindingResolutionException
* @codeCoverageIgnore
*/
public function onMessageRemoved(callable|string $handler): void
{
$this->dispatcher->onMessageRemoved($this->resolveHandler($handler));
}
/**
* Register a bot added handler.
*
* @param callable|string $handler Can be a closure, callable, or Laravel container binding.
*
* @throws BindingResolutionException
* @codeCoverageIgnore
*/
public function onBotAdded(callable|string $handler): void
{
$this->dispatcher->onBotAdded($this->resolveHandler($handler));
}
/**
* Register a bot removed handler.
*
* @param callable|string $handler Can be a closure, callable, or Laravel container binding.
*
* @throws BindingResolutionException
* @codeCoverageIgnore
*/
public function onBotRemoved(callable|string $handler): void
{
$this->dispatcher->onBotRemoved($this->resolveHandler($handler));
}
/**
* Register a user added handler.
*
* @param callable|string $handler Can be a closure, callable, or Laravel container binding.
*
* @throws BindingResolutionException
* @codeCoverageIgnore
*/
public function onUserAdded(callable|string $handler): void
{
$this->dispatcher->onUserAdded($this->resolveHandler($handler));
}
/**
* Register a user removed handler.
*
* @param callable|string $handler Can be a closure, callable, or Laravel container binding.
*
* @throws BindingResolutionException
* @codeCoverageIgnore
*/
public function onUserRemoved(callable|string $handler): void
{
$this->dispatcher->onUserRemoved($this->resolveHandler($handler));
}
/**
* Register a bot started handler.
*
* @param callable|string $handler Can be a closure, callable, or Laravel container binding.
*
* @throws BindingResolutionException
* @codeCoverageIgnore
*/
public function onBotStarted(callable|string $handler): void
{
$this->dispatcher->onBotStarted($this->resolveHandler($handler));
}
/**
* Register a chat title changed handler.
*
* @param callable|string $handler Can be a closure, callable, or Laravel container binding.
*
* @throws BindingResolutionException
* @codeCoverageIgnore
*/
public function onChatTitleChanged(callable|string $handler): void
{
$this->dispatcher->onChatTitleChanged($this->resolveHandler($handler));
}
/**
* Register a message chat created handler.
*
* @param callable|string $handler Can be a closure, callable, or Laravel container binding.
*
* @throws BindingResolutionException
* @codeCoverageIgnore
*/
public function onMessageChatCreated(callable|string $handler): void
{
$this->dispatcher->onMessageChatCreated($this->resolveHandler($handler));
}
/**
* Get the API instance.
* @codeCoverageIgnore
*/
public function getApi(): Api
{
return $this->api;
}
/**
* Get the update dispatcher.
* @codeCoverageIgnore
*/
public function getDispatcher(): UpdateDispatcher
{
return $this->dispatcher;
}
/**
* Resolve a handler that might be a Laravel container binding.
*
* @param callable|string $handler
* @return callable
* @phpstan-return callable(AbstractUpdate, Api): void
* @throws BindingResolutionException
*/
private function resolveHandler(callable|string $handler): callable
{
if (is_string($handler)) {
if ($this->container->bound($handler)) {
$resolved = $this->container->make($handler);
if (is_callable($resolved)) {
return $resolved;
}
if (is_object($resolved) && method_exists($resolved, 'handle')) {
/** @var callable */
return [$resolved, 'handle'];
}
throw new \InvalidArgumentException(
"Handler class '$handler' is not callable and doesn't have a handle method."
);
}
if (str_contains($handler, '@')) {
[$class, $method] = explode('@', $handler, 2);
$instance = $this->container->make($class);
/** @var callable */
return [$instance, $method];
}
if (class_exists($handler)) {
$instance = $this->container->make($handler);
if (method_exists($instance, 'handle')) {
/** @var callable */
return [$instance, 'handle'];
}
}
throw new \InvalidArgumentException("Unable to resolve handler: $handler");
}
return $handler;
}
}
+193
View File
@@ -0,0 +1,193 @@
<?php
declare(strict_types=1);
namespace BushlanovDev\MaxMessengerBot\Laravel;
use BushlanovDev\MaxMessengerBot\Api;
use BushlanovDev\MaxMessengerBot\Client;
use BushlanovDev\MaxMessengerBot\ClientApiInterface;
use BushlanovDev\MaxMessengerBot\Laravel\Commands\PollingStartCommand;
use BushlanovDev\MaxMessengerBot\ModelFactory;
use BushlanovDev\MaxMessengerBot\UpdateDispatcher;
use BushlanovDev\MaxMessengerBot\WebhookHandler;
use BushlanovDev\MaxMessengerBot\LongPollingHandler;
use BushlanovDev\MaxMessengerBot\Laravel\Commands\WebhookSubscribeCommand;
use BushlanovDev\MaxMessengerBot\Laravel\Commands\WebhookUnsubscribeCommand;
use BushlanovDev\MaxMessengerBot\Laravel\Commands\WebhookListCommand;
use Illuminate\Contracts\Foundation\Application;
use Illuminate\Support\ServiceProvider;
use Illuminate\Contracts\Config\Repository as Config;
use Psr\Log\LoggerInterface;
use InvalidArgumentException;
use Psr\Log\NullLogger;
/**
* Laravel Service Provider for Max Bot API Client.
* Registers all necessary services in the Laravel container.
*/
class MaxBotServiceProvider extends ServiceProvider
{
/**
* Register any application services.
*/
public function register(): void
{
$this->mergeConfigFrom(
__DIR__ . '/config/maxbot.php',
'maxbot',
);
$this->app->singleton(ClientApiInterface::class, function (Application $app) {
/** @var Config $config */
$config = $app->make(Config::class);
$accessToken = $config->get('maxbot.access_token');
if (empty($accessToken)) {
throw new InvalidArgumentException(
'Max Bot access token is not configured. Please set MAXBOT_ACCESS_TOKEN in your .env file.'
);
}
if (!class_exists(\GuzzleHttp\Client::class) || !class_exists(\GuzzleHttp\Psr7\HttpFactory::class)) {
throw new \LogicException(
'Guzzle HTTP client is required. Please run "composer require guzzlehttp/guzzle".'
);
}
$logger = $config->get('maxbot.logging.enabled', false)
? $app->make(LoggerInterface::class)
: new NullLogger();
$guzzle = new \GuzzleHttp\Client([
'timeout' => (int)$config->get('maxbot.timeout', 10),
'connect_timeout' => (int)$config->get('maxbot.connect_timeout', 5),
'read_timeout' => (int)$config->get('maxbot.read_timeout', 10),
'headers' => [
'User-Agent' => 'max-bot-api-client-php/' . Api::LIBRARY_VERSION
. ' Laravel/' . $app->version() . ' PHP/' . PHP_VERSION
],
]);
$httpFactory = new \GuzzleHttp\Psr7\HttpFactory();
return new Client(
$accessToken,
$guzzle,
$httpFactory,
$httpFactory,
$config->get('maxbot.base_url', 'https://botapi.max.ru'),
$config->get('maxbot.api_version', Api::API_VERSION),
$logger,
);
});
$this->app->singleton(ModelFactory::class, function () {
return new ModelFactory();
});
$this->app->singleton(Api::class, function (Application $app) {
/** @var Config $config */
$config = $app->make(Config::class);
$accessToken = $config->get('maxbot.access_token');
if (empty($accessToken)) {
throw new InvalidArgumentException(
'Max Bot access token is not configured. Please set MAXBOT_ACCESS_TOKEN in your .env file.'
);
}
return new Api(
$accessToken,
$app->make(ClientApiInterface::class),
$app->make(ModelFactory::class),
$app->make(LoggerInterface::class),
);
});
$this->app->singleton(UpdateDispatcher::class, function (Application $app) {
return $app->make(Api::class)->getUpdateDispatcher();
});
$this->app->bind(WebhookHandler::class, function (Application $app) {
/** @var Config $config */
$config = $app->make(Config::class);
$secret = $config->get('maxbot.webhook_secret');
return new WebhookHandler(
$app->make(UpdateDispatcher::class),
$app->make(ModelFactory::class),
$app->make(LoggerInterface::class),
$secret,
);
});
$this->app->bind(LongPollingHandler::class, function (Application $app) {
return new LongPollingHandler(
$app->make(Api::class),
$app->make(UpdateDispatcher::class),
$app->make(LoggerInterface::class),
);
});
$this->app->singleton(MaxBotManager::class, function (Application $app) {
return new MaxBotManager(
$app,
$app->make(Api::class),
$app->make(UpdateDispatcher::class),
);
});
$this->app->alias(Api::class, 'maxbot');
$this->app->alias(Api::class, 'maxbot.api');
$this->app->alias(ClientApiInterface::class, 'maxbot.client');
$this->app->alias(UpdateDispatcher::class, 'maxbot.dispatcher');
$this->app->alias(WebhookHandler::class, 'maxbot.webhook');
$this->app->alias(LongPollingHandler::class, 'maxbot.polling');
$this->app->alias(MaxBotManager::class, 'maxbot.manager');
}
/**
* Bootstrap any application services.
*/
public function boot(): void
{
$this->publishes([
__DIR__ . '/config/maxbot.php' => $this->app->configPath('maxbot.php'),
], 'maxbot-config');
if ($this->app->runningInConsole()) {
$this->commands([
WebhookSubscribeCommand::class,
WebhookUnsubscribeCommand::class,
WebhookListCommand::class,
PollingStartCommand::class,
]);
}
}
/**
* Get the services provided by the provider.
*
* @return array<int, string>
*/
public function provides(): array
{
return [
Api::class,
ClientApiInterface::class,
ModelFactory::class,
UpdateDispatcher::class,
WebhookHandler::class,
LongPollingHandler::class,
MaxBotManager::class,
'maxbot',
'maxbot.api',
'maxbot.client',
'maxbot.dispatcher',
'maxbot.webhook',
'maxbot.polling',
'maxbot.manager',
];
}
}
+69
View File
@@ -0,0 +1,69 @@
<?php
declare(strict_types=1);
// @codeCoverageIgnoreStart
return [
/*
|--------------------------------------------------------------------------
| Max Bot Access Token
|--------------------------------------------------------------------------
|
| Your bot's access token from @MasterBot. This token is required for
| authentication with the Max Bot API. You can obtain it by creating
| a bot through @MasterBot in the Max messenger.
|
*/
'access_token' => env('MAXBOT_ACCESS_TOKEN'),
/*
|--------------------------------------------------------------------------
| Webhook Secret
|--------------------------------------------------------------------------
|
| Secret key for verifying the authenticity of webhook requests.
| This is optional but recommended for security. Set this if you're
| using webhooks to receive updates.
|
*/
'webhook_secret' => env('MAXBOT_WEBHOOK_SECRET'),
/*
|--------------------------------------------------------------------------
| API Configuration
|--------------------------------------------------------------------------
|
| Configuration for the Max Bot API connection.
|
*/
'base_url' => env('MAXBOT_BASE_URL', 'https://botapi.max.ru'),
'api_version' => env('MAXBOT_API_VERSION'),
/*
|--------------------------------------------------------------------------
| HTTP Client Configuration
|--------------------------------------------------------------------------
|
| Configuration for the HTTP client used to communicate with the API.
| All values are in seconds.
|
*/
'timeout' => (int)env('MAXBOT_TIMEOUT', 10),
'connect_timeout' => (int)env('MAXBOT_CONNECT_TIMEOUT', 5),
'read_timeout' => (int)env('MAXBOT_READ_TIMEOUT', 10),
/*
|--------------------------------------------------------------------------
| Logging Configuration
|--------------------------------------------------------------------------
|
| Whether to enable detailed logging of API requests and responses.
| This uses Laravel's configured logger.
|
*/
'logging' => [
'enabled' => (bool)env('MAXBOT_LOGGING_ENABLED', false),
'level' => env('MAXBOT_LOGGING_LEVEL', 'debug'),
],
];
// @codeCoverageIgnoreEnd
+104
View File
@@ -0,0 +1,104 @@
<?php
declare(strict_types=1);
namespace BushlanovDev\MaxMessengerBot;
use BushlanovDev\MaxMessengerBot\Exceptions\NetworkException;
use Psr\Log\LoggerInterface;
/**
* Handles receiving updates via long polling.
*/
final readonly class LongPollingHandler
{
/**
* @param Api $api
* @param UpdateDispatcher $dispatcher The update dispatcher.
* @param LoggerInterface $logger PSR LoggerInterface.
* @codeCoverageIgnore
*/
public function __construct(
private Api $api,
private UpdateDispatcher $dispatcher,
private LoggerInterface $logger,
) {
if (!(\PHP_SAPI === 'cli')) {
throw new \RuntimeException('LongPollingHandler can only be used in CLI mode.');
}
}
/**
* Processes a single batch of updates. Useful for custom loop implementations or for testing.
*
* @param int $timeout Timeout for the getUpdates call.
* @param int|null $marker The marker for which updates to fetch.
* @return int|null The new marker to be used for the next iteration.
* @throws \Exception Re-throws exceptions from the API or dispatcher.
*/
public function processUpdates(int $timeout, ?int $marker): ?int
{
$updateList = $this->api->getUpdates(timeout: $timeout, marker: $marker);
foreach ($updateList->updates as $update) {
try {
$this->dispatcher->dispatch($update);
} catch (\Throwable $e) {
$this->logger->error('Error dispatching update', [
'message' => $e->getMessage(),
'exception' => $e,
]);
}
}
return $updateList->marker;
}
/**
* Starts a long-polling loop to process updates.
* This method will run indefinitely until the script is terminated.
*
* @param int $timeout Timeout in seconds for long polling (0-90).
* @param int|null $marker Initial marker. Pass `null` to get updates you didn't get yet.
*/
public function handle(int $timeout = 90, ?int $marker = null): void
{
$this->listenSignals();
// @phpstan-ignore-next-line
while (true) {
try {
$marker = $this->processUpdates($timeout, $marker);
} catch (NetworkException $e) {
$this->logger->error(
'Long-polling network error: {message}',
['message' => $e->getMessage(), 'exception' => $e],
);
sleep(5);
} catch (\Exception $e) {
$this->logger->error(
'An error occurred during long-polling: {message}',
['message' => $e->getMessage(), 'exception' => $e],
);
sleep(1);
}
}
}
/**
* @codeCoverageIgnore
*/
protected function listenSignals(): void
{
if (extension_loaded('pcntl')) {
pcntl_async_signals(true);
$kill = static function () {
exit(0);
};
pcntl_signal(SIGINT, $kill);
pcntl_signal(SIGQUIT, $kill);
pcntl_signal(SIGTERM, $kill);
}
}
}
+236
View File
@@ -4,11 +4,51 @@ declare(strict_types=1);
namespace BushlanovDev\MaxMessengerBot;
use BushlanovDev\MaxMessengerBot\Enums\AttachmentType;
use BushlanovDev\MaxMessengerBot\Enums\InlineButtonType;
use BushlanovDev\MaxMessengerBot\Enums\MarkupType;
use BushlanovDev\MaxMessengerBot\Enums\ReplyButtonType;
use BushlanovDev\MaxMessengerBot\Enums\UpdateType;
use BushlanovDev\MaxMessengerBot\Models\Attachments\AbstractAttachment;
use BushlanovDev\MaxMessengerBot\Models\Attachments\AudioAttachment;
use BushlanovDev\MaxMessengerBot\Models\Attachments\Buttons\Inline\AbstractInlineButton;
use BushlanovDev\MaxMessengerBot\Models\Attachments\Buttons\Inline\CallbackButton;
use BushlanovDev\MaxMessengerBot\Models\Attachments\Buttons\Inline\ChatButton;
use BushlanovDev\MaxMessengerBot\Models\Attachments\Buttons\Inline\LinkButton;
use BushlanovDev\MaxMessengerBot\Models\Attachments\Buttons\Inline\OpenAppButton;
use BushlanovDev\MaxMessengerBot\Models\Attachments\Buttons\Inline\RequestContactButton;
use BushlanovDev\MaxMessengerBot\Models\Attachments\Buttons\Inline\RequestGeoLocationButton;
use BushlanovDev\MaxMessengerBot\Models\Attachments\Buttons\Reply\AbstractReplyButton;
use BushlanovDev\MaxMessengerBot\Models\Attachments\Buttons\Reply\SendContactButton;
use BushlanovDev\MaxMessengerBot\Models\Attachments\Buttons\Reply\SendGeoLocationButton;
use BushlanovDev\MaxMessengerBot\Models\Attachments\Buttons\Reply\SendMessageButton;
use BushlanovDev\MaxMessengerBot\Models\Attachments\ContactAttachment;
use BushlanovDev\MaxMessengerBot\Models\Attachments\DataAttachment;
use BushlanovDev\MaxMessengerBot\Models\Attachments\FileAttachment;
use BushlanovDev\MaxMessengerBot\Models\Attachments\InlineKeyboardAttachment;
use BushlanovDev\MaxMessengerBot\Models\Attachments\LocationAttachment;
use BushlanovDev\MaxMessengerBot\Models\Attachments\PhotoAttachment;
use BushlanovDev\MaxMessengerBot\Models\Attachments\ReplyKeyboardAttachment;
use BushlanovDev\MaxMessengerBot\Models\Attachments\ShareAttachment;
use BushlanovDev\MaxMessengerBot\Models\Attachments\StickerAttachment;
use BushlanovDev\MaxMessengerBot\Models\Attachments\VideoAttachment;
use BushlanovDev\MaxMessengerBot\Models\BotInfo;
use BushlanovDev\MaxMessengerBot\Models\Chat;
use BushlanovDev\MaxMessengerBot\Models\ChatList;
use BushlanovDev\MaxMessengerBot\Models\ChatMember;
use BushlanovDev\MaxMessengerBot\Models\ChatMembersList;
use BushlanovDev\MaxMessengerBot\Models\Markup\AbstractMarkup;
use BushlanovDev\MaxMessengerBot\Models\Markup\EmphasizedMarkup;
use BushlanovDev\MaxMessengerBot\Models\Markup\HeadingMarkup;
use BushlanovDev\MaxMessengerBot\Models\Markup\HighlightedMarkup;
use BushlanovDev\MaxMessengerBot\Models\Markup\LinkMarkup;
use BushlanovDev\MaxMessengerBot\Models\Markup\MonospacedMarkup;
use BushlanovDev\MaxMessengerBot\Models\Markup\StrikethroughMarkup;
use BushlanovDev\MaxMessengerBot\Models\Markup\StrongMarkup;
use BushlanovDev\MaxMessengerBot\Models\Markup\UnderlineMarkup;
use BushlanovDev\MaxMessengerBot\Models\Markup\UserMentionMarkup;
use BushlanovDev\MaxMessengerBot\Models\Message;
use BushlanovDev\MaxMessengerBot\Models\MessageBody;
use BushlanovDev\MaxMessengerBot\Models\Result;
use BushlanovDev\MaxMessengerBot\Models\Subscription;
use BushlanovDev\MaxMessengerBot\Models\UpdateList;
@@ -25,6 +65,7 @@ use BushlanovDev\MaxMessengerBot\Models\Updates\MessageRemovedUpdate;
use BushlanovDev\MaxMessengerBot\Models\Updates\UserAddedToChatUpdate;
use BushlanovDev\MaxMessengerBot\Models\Updates\UserRemovedFromChatUpdate;
use BushlanovDev\MaxMessengerBot\Models\UploadEndpoint;
use BushlanovDev\MaxMessengerBot\Models\VideoAttachmentDetails;
use LogicException;
use ReflectionException;
@@ -97,9 +138,139 @@ class ModelFactory
*/
public function createMessage(array $data): Message
{
if (isset($data['body']) && is_array($data['body'])) {
$data['body'] = $this->createMessageBody($data['body']);
}
return Message::fromArray($data);
}
/**
* List of messages.
*
* @param array<string, mixed> $data
*
* @return Message[]
*/
public function createMessages(array $data): array
{
return isset($data['messages']) && is_array($data['messages'])
? array_map([$this, 'createMessage'], $data['messages'])
: [];
}
/**
* Creates a MessageBody object from raw API data, handling polymorphic attachments and markup.
*
* @param array<string, mixed> $data
*
* @return MessageBody
* @throws ReflectionException
*/
private function createMessageBody(array $data): MessageBody
{
if (isset($data['attachments']) && is_array($data['attachments'])) {
$data['attachments'] = array_map(
[$this, 'createAttachment'],
$data['attachments'],
);
}
if (isset($data['markup']) && is_array($data['markup'])) {
$data['markup'] = array_map(
[$this, 'createMarkupElement'],
$data['markup'],
);
}
return MessageBody::fromArray($data);
}
/**
* Creates a specific Attachment model based on the 'type' field.
*
* @param array<string, mixed> $data
*
* @return AbstractAttachment
* @throws ReflectionException
*/
public function createAttachment(array $data): AbstractAttachment
{
$attachmentType = AttachmentType::tryFrom($data['type'] ?? '');
if ($attachmentType === AttachmentType::ReplyKeyboard
&& isset($data['buttons']) && is_array($data['buttons'])) {
$data['buttons'] = array_map(
fn($rowOfButtons) => array_map([$this, 'createReplyButton'], $rowOfButtons),
$data['buttons'],
);
}
if ($attachmentType === AttachmentType::InlineKeyboard
&& isset($data['payload']['buttons']) && is_array($data['payload']['buttons'])) {
$data['payload']['buttons'] = array_map(
fn($rowOfButtons) => array_map([$this, 'createInlineButton'], $rowOfButtons),
$data['payload']['buttons']
);
}
return match ($attachmentType) {
AttachmentType::Data => DataAttachment::fromArray($data),
AttachmentType::Share => ShareAttachment::fromArray($data),
AttachmentType::Image => PhotoAttachment::fromArray($data),
AttachmentType::Video => VideoAttachment::fromArray($data),
AttachmentType::Audio => AudioAttachment::fromArray($data),
AttachmentType::File => FileAttachment::fromArray($data),
AttachmentType::Sticker => StickerAttachment::fromArray($data),
AttachmentType::Contact => ContactAttachment::fromArray($data),
AttachmentType::InlineKeyboard => InlineKeyboardAttachment::fromArray($data),
AttachmentType::ReplyKeyboard => ReplyKeyboardAttachment::fromArray($data),
AttachmentType::Location => LocationAttachment::fromArray($data),
default => throw new LogicException('Unknown or unsupported attachment type: ' . ($data['type'] ?? 'none')),
};
}
/**
* Creates a specific ReplyButton model based on the 'type' field.
*
* @param array<string, mixed> $data
*
* @return AbstractReplyButton
* @throws ReflectionException
* @throws LogicException
*/
public function createReplyButton(array $data): AbstractReplyButton
{
return match (ReplyButtonType::tryFrom($data['type'] ?? '')) {
ReplyButtonType::Message => SendMessageButton::fromArray($data),
ReplyButtonType::UserContact => SendContactButton::fromArray($data),
ReplyButtonType::UserGeoLocation => SendGeoLocationButton::fromArray($data),
default => throw new LogicException(
'Unknown or unsupported reply button type: ' . ($data['type'] ?? 'none')
),
};
}
/**
* Creates a specific InlineButton model based on the 'type' field.
*
* @param array<string, mixed> $data
* @return AbstractInlineButton
* @throws ReflectionException
* @throws LogicException
*/
public function createInlineButton(array $data): AbstractInlineButton
{
return match (InlineButtonType::tryFrom($data['type'] ?? '')) {
InlineButtonType::Callback => CallbackButton::fromArray($data),
InlineButtonType::Link => LinkButton::fromArray($data),
InlineButtonType::RequestContact => RequestContactButton::fromArray($data),
InlineButtonType::RequestGeoLocation => RequestGeoLocationButton::fromArray($data),
InlineButtonType::Chat => ChatButton::fromArray($data),
InlineButtonType::OpenApp => OpenAppButton::fromArray($data),
default => throw new LogicException('Unknown or unsupported inline button type: ' . ($data['type'] ?? 'none')),
};
}
/**
* Endpoint you should upload to your binaries.
*
@@ -192,4 +363,69 @@ class ModelFactory
{
return ChatList::fromArray($data);
}
/**
* Creates a ChatMember object from raw API data.
*
* @param array<string, mixed> $data
*
* @return ChatMember
* @throws ReflectionException
*/
public function createChatMember(array $data): ChatMember
{
return ChatMember::fromArray($data);
}
/**
* Creates a ChatMembersList object from raw API data.
*
* @param array<string, mixed> $data
*
* @return ChatMembersList
* @throws ReflectionException
*/
public function createChatMembersList(array $data): ChatMembersList
{
return ChatMembersList::fromArray($data);
}
/**
* Creates a VideoAttachmentDetails object from raw API data.
*
* @param array<string, mixed> $data
*
* @return VideoAttachmentDetails
* @throws ReflectionException
*/
public function createVideoAttachmentDetails(array $data): VideoAttachmentDetails
{
return VideoAttachmentDetails::fromArray($data);
}
/**
* Creates a specific Markup model based on the 'type' field.
*
* @param array<string, mixed> $data
*
* @return AbstractMarkup
* @throws ReflectionException
*/
public function createMarkupElement(array $data): AbstractMarkup
{
return match (MarkupType::tryFrom($data['type'] ?? '')) {
MarkupType::Strong => StrongMarkup::fromArray($data),
MarkupType::Emphasized => EmphasizedMarkup::fromArray($data),
MarkupType::Monospaced => MonospacedMarkup::fromArray($data),
MarkupType::Strikethrough => StrikethroughMarkup::fromArray($data),
MarkupType::Underline => UnderlineMarkup::fromArray($data),
MarkupType::Heading => HeadingMarkup::fromArray($data),
MarkupType::Highlighted => HighlightedMarkup::fromArray($data),
MarkupType::Link => LinkMarkup::fromArray($data),
MarkupType::UserMention => UserMentionMarkup::fromArray($data),
default => throw new LogicException(
'Unknown or unsupported markup type: ' . ($data['type'] ?? 'none')
),
};
}
}
+68 -61
View File
@@ -42,6 +42,65 @@ abstract readonly class AbstractModel
return new static(...$constructorArgs); // @phpstan-ignore-line
}
/**
* @return array<string, mixed>
* @throws ReflectionException
*/
public function toArray(): array
{
$reflectionClass = new ReflectionClass($this);
$properties = $reflectionClass->getProperties(ReflectionProperty::IS_PUBLIC);
$result = [];
foreach ($properties as $property) {
if (!$property->isInitialized($this)) {
continue;
}
$phpPropertyName = $property->getName();
$value = $property->getValue($this);
$jsonKey = self::toSnakeCase($phpPropertyName);
$result[$jsonKey] = $this->convertValue($value);
}
return $result;
}
/**
* @param string $input
*
* @return string
*/
protected static function toSnakeCase(string $input): string
{
return strtolower((string)preg_replace('/(?<!^)[A-Z]/', '_$0', $input));
}
/**
* @param mixed $value
*
* @return mixed
* @throws ReflectionException
*/
protected function convertValue(mixed $value): mixed
{
if ($value instanceof AbstractModel) {
return $value->toArray();
}
if (is_array($value)) {
return array_map([$this, 'convertValue'], $value);
}
if ($value instanceof BackedEnum) {
return $value->value;
}
return $value;
}
/**
* @param mixed $value
* @param ReflectionProperty $property
@@ -59,6 +118,10 @@ abstract readonly class AbstractModel
$typeName = $type->getName();
if (is_object($value) && is_a($value, $typeName)) {
return $value;
}
if ($type->isBuiltin()) {
return match ($typeName) {
'int' => (int)$value,
@@ -74,7 +137,7 @@ abstract readonly class AbstractModel
return $typeName::from($value);
}
if (is_subclass_of($typeName, self::class)) {
if (is_subclass_of($typeName, self::class) && is_array($value)) {
return $typeName::fromArray($value);
}
@@ -109,66 +172,10 @@ abstract readonly class AbstractModel
}
if (is_subclass_of($itemClassName, self::class)) {
return array_map(fn($item) => $itemClassName::fromArray($item), $value);
}
return $value;
}
/**
* @param string $input
*
* @return string
*/
private static function toSnakeCase(string $input): string
{
return strtolower((string)preg_replace('/(?<!^)[A-Z]/', '_$0', $input));
}
/**
* @return array<string, mixed>
* @throws ReflectionException
*/
public function toArray(): array
{
$reflectionClass = new ReflectionClass($this);
$properties = $reflectionClass->getProperties(ReflectionProperty::IS_PUBLIC);
$result = [];
foreach ($properties as $property) {
if (!$property->isInitialized($this)) {
continue;
}
$phpPropertyName = $property->getName();
$value = $property->getValue($this);
$jsonKey = self::toSnakeCase($phpPropertyName);
$result[$jsonKey] = $this->convertValue($value);
}
return $result;
}
/**
* @param mixed $value
*
* @return mixed
* @throws ReflectionException
*/
private function convertValue(mixed $value): mixed
{
if ($value instanceof AbstractModel) {
return $value->toArray();
}
if (is_array($value)) {
return array_map([$this, 'convertValue'], $value);
}
if ($value instanceof BackedEnum) {
return $value->value;
return array_map(
fn($item) => is_a($item, $itemClassName) ? $item : $itemClassName::fromArray($item),
$value,
);
}
return $value;
+42
View File
@@ -0,0 +1,42 @@
<?php
declare(strict_types=1);
namespace BushlanovDev\MaxMessengerBot\Models;
/**
* An abstract base for PATCH request models. It uses a variadic constructor
* to capture named arguments, tracking which fields were explicitly set.
*/
abstract readonly class AbstractPatchModel extends AbstractModel
{
/**
* @var array<int|string, mixed>
*/
protected array $patchData;
/**
* Captures all passed named arguments into an associative array.
*
* @param mixed ...$params
*/
public function __construct(...$params)
{
$this->patchData = $params;
}
/**
* @return array<string, mixed>
* @throws \ReflectionException
*/
final public function toArray(): array
{
$result = [];
foreach ($this->patchData as $key => $value) {
$jsonKey = $this->toSnakeCase((string)$key);
$result[$jsonKey] = $this->convertValue($value);
}
return $result;
}
}
@@ -0,0 +1,18 @@
<?php
declare(strict_types=1);
namespace BushlanovDev\MaxMessengerBot\Models\Attachments;
use BushlanovDev\MaxMessengerBot\Enums\AttachmentType;
use BushlanovDev\MaxMessengerBot\Models\AbstractModel;
/**
* Represents a generic attachment received from the API.
*/
abstract readonly class AbstractAttachment extends AbstractModel
{
public function __construct(public AttachmentType $type)
{
}
}
@@ -0,0 +1,22 @@
<?php
declare(strict_types=1);
namespace BushlanovDev\MaxMessengerBot\Models\Attachments;
use BushlanovDev\MaxMessengerBot\Enums\AttachmentType;
use BushlanovDev\MaxMessengerBot\Models\Attachments\Payloads\MediaAttachmentPayload;
final readonly class AudioAttachment extends AbstractAttachment
{
/**
* @param MediaAttachmentPayload $payload Audio attachment payload.
* @param string|null $transcription Audio transcription.
*/
public function __construct(
public MediaAttachmentPayload $payload,
public ?string $transcription,
) {
parent::__construct(AttachmentType::Audio);
}
}
@@ -1,17 +0,0 @@
<?php
declare(strict_types=1);
namespace BushlanovDev\MaxMessengerBot\Models\Attachments\Buttons;
use BushlanovDev\MaxMessengerBot\Enums\ButtonType;
use BushlanovDev\MaxMessengerBot\Models\AbstractModel;
abstract readonly class AbstractButton extends AbstractModel
{
public function __construct(
public ButtonType $type,
public string $text,
) {
}
}
@@ -0,0 +1,21 @@
<?php
declare(strict_types=1);
namespace BushlanovDev\MaxMessengerBot\Models\Attachments\Buttons\Inline;
use BushlanovDev\MaxMessengerBot\Enums\InlineButtonType;
use BushlanovDev\MaxMessengerBot\Models\AbstractModel;
abstract readonly class AbstractInlineButton extends AbstractModel
{
/**
* @param InlineButtonType $type The type of the inline button.
* @param string $text Visible text of the button.
*/
public function __construct(
public InlineButtonType $type,
public string $text,
) {
}
}
@@ -2,15 +2,15 @@
declare(strict_types=1);
namespace BushlanovDev\MaxMessengerBot\Models\Attachments\Buttons;
namespace BushlanovDev\MaxMessengerBot\Models\Attachments\Buttons\Inline;
use BushlanovDev\MaxMessengerBot\Enums\ButtonType;
use BushlanovDev\MaxMessengerBot\Enums\InlineButtonType;
use BushlanovDev\MaxMessengerBot\Enums\Intent;
/**
* Sends a notification with payload to a bot (via WebHook or long polling).
*/
final readonly class CallbackButton extends AbstractButton
final readonly class CallbackButton extends AbstractInlineButton
{
public string $payload;
public ?Intent $intent;
@@ -22,7 +22,7 @@ final readonly class CallbackButton extends AbstractButton
*/
public function __construct(string $text, string $payload, ?Intent $intent = null)
{
parent::__construct(ButtonType::Callback, $text);
parent::__construct(InlineButtonType::Callback, $text);
$this->payload = $payload;
$this->intent = $intent;
@@ -0,0 +1,31 @@
<?php
declare(strict_types=1);
namespace BushlanovDev\MaxMessengerBot\Models\Attachments\Buttons\Inline;
use BushlanovDev\MaxMessengerBot\Enums\InlineButtonType;
/**
* Button that creates a new chat associated with the message.
* The bot will be added as an administrator by default.
*/
final readonly class ChatButton extends AbstractInlineButton
{
/**
* @param string $text Visible text of the button (1 to 128 characters).
* @param string $chatTitle Title of the chat to be created (max 200 characters).
* @param string|null $chatDescription Optional chat description (max 400 characters).
* @param string|null $startPayload Optional payload that will be sent to the bot in a `message_chat_created` update.
* @param int|null $uuid Optional unique identifier for the button. If not passed, it will be generated.
*/
public function __construct(
string $text,
public string $chatTitle,
public ?string $chatDescription = null,
public ?string $startPayload = null,
public ?int $uuid = null,
) {
parent::__construct(InlineButtonType::Chat, $text);
}
}
@@ -2,14 +2,14 @@
declare(strict_types=1);
namespace BushlanovDev\MaxMessengerBot\Models\Attachments\Buttons;
namespace BushlanovDev\MaxMessengerBot\Models\Attachments\Buttons\Inline;
use BushlanovDev\MaxMessengerBot\Enums\ButtonType;
use BushlanovDev\MaxMessengerBot\Enums\InlineButtonType;
/**
* Makes a user to follow a link.
*/
final readonly class LinkButton extends AbstractButton
final readonly class LinkButton extends AbstractInlineButton
{
public string $url;
@@ -19,7 +19,7 @@ final readonly class LinkButton extends AbstractButton
*/
public function __construct(string $text, string $url)
{
parent::__construct(ButtonType::Link, $text);
parent::__construct(InlineButtonType::Link, $text);
$this->url = $url;
}
@@ -2,14 +2,14 @@
declare(strict_types=1);
namespace BushlanovDev\MaxMessengerBot\Models\Attachments\Buttons;
namespace BushlanovDev\MaxMessengerBot\Models\Attachments\Buttons\Inline;
use BushlanovDev\MaxMessengerBot\Enums\ButtonType;
use BushlanovDev\MaxMessengerBot\Enums\InlineButtonType;
/**
* Opens the bot's mini-application.
*/
final readonly class OpenAppButton extends AbstractButton
final readonly class OpenAppButton extends AbstractInlineButton
{
public ?string $webApp;
public ?int $contactId;
@@ -21,7 +21,7 @@ final readonly class OpenAppButton extends AbstractButton
*/
public function __construct(string $text, ?string $webApp = null, ?int $contactId = null)
{
parent::__construct(ButtonType::OpenApp, $text);
parent::__construct(InlineButtonType::OpenApp, $text);
$this->webApp = $webApp;
$this->contactId = $contactId;
@@ -2,20 +2,20 @@
declare(strict_types=1);
namespace BushlanovDev\MaxMessengerBot\Models\Attachments\Buttons;
namespace BushlanovDev\MaxMessengerBot\Models\Attachments\Buttons\Inline;
use BushlanovDev\MaxMessengerBot\Enums\ButtonType;
use BushlanovDev\MaxMessengerBot\Enums\InlineButtonType;
/**
* Requests the user permission to access contact information (phone number, short link, email).
*/
final readonly class RequestContactButton extends AbstractButton
final readonly class RequestContactButton extends AbstractInlineButton
{
/**
* @param string $text Visible button text (1 to 128 characters).
*/
public function __construct(string $text)
{
parent::__construct(ButtonType::RequestContact, $text);
parent::__construct(InlineButtonType::RequestContact, $text);
}
}
@@ -2,14 +2,14 @@
declare(strict_types=1);
namespace BushlanovDev\MaxMessengerBot\Models\Attachments\Buttons;
namespace BushlanovDev\MaxMessengerBot\Models\Attachments\Buttons\Inline;
use BushlanovDev\MaxMessengerBot\Enums\ButtonType;
use BushlanovDev\MaxMessengerBot\Enums\InlineButtonType;
/**
* After pressing this type of button client sends new message with attachment of current user geo location.
*/
final readonly class RequestGeoLocationButton extends AbstractButton
final readonly class RequestGeoLocationButton extends AbstractInlineButton
{
public bool $quick;
@@ -19,7 +19,7 @@ final readonly class RequestGeoLocationButton extends AbstractButton
*/
public function __construct(string $text, bool $quick = false)
{
parent::__construct(ButtonType::RequestGeoLocation, $text);
parent::__construct(InlineButtonType::RequestGeoLocation, $text);
$this->quick = $quick;
}
@@ -0,0 +1,21 @@
<?php
declare(strict_types=1);
namespace BushlanovDev\MaxMessengerBot\Models\Attachments\Buttons\Reply;
use BushlanovDev\MaxMessengerBot\Enums\ReplyButtonType;
use BushlanovDev\MaxMessengerBot\Models\AbstractModel;
abstract readonly class AbstractReplyButton extends AbstractModel
{
/**
* @param ReplyButtonType $type The type of the reply button.
* @param string $text Visible text of the button.
*/
public function __construct(
public ReplyButtonType $type,
public string $text,
) {
}
}
@@ -0,0 +1,18 @@
<?php
declare(strict_types=1);
namespace BushlanovDev\MaxMessengerBot\Models\Attachments\Buttons\Reply;
use BushlanovDev\MaxMessengerBot\Enums\ReplyButtonType;
final readonly class SendContactButton extends AbstractReplyButton
{
/**
* @param string $text Visible text of the button.
*/
public function __construct(string $text)
{
parent::__construct(ReplyButtonType::UserContact, $text);
}
}
@@ -0,0 +1,21 @@
<?php
declare(strict_types=1);
namespace BushlanovDev\MaxMessengerBot\Models\Attachments\Buttons\Reply;
use BushlanovDev\MaxMessengerBot\Enums\ReplyButtonType;
final readonly class SendGeoLocationButton extends AbstractReplyButton
{
/**
* @param string $text Visible text of the button.
* @param bool $quick If `true`, sends location without asking user's confirmation.
*/
public function __construct(
string $text,
public bool $quick = false,
) {
parent::__construct(ReplyButtonType::UserGeoLocation, $text);
}
}
@@ -0,0 +1,24 @@
<?php
declare(strict_types=1);
namespace BushlanovDev\MaxMessengerBot\Models\Attachments\Buttons\Reply;
use BushlanovDev\MaxMessengerBot\Enums\Intent;
use BushlanovDev\MaxMessengerBot\Enums\ReplyButtonType;
final readonly class SendMessageButton extends AbstractReplyButton
{
/**
* @param string $text Visible text of the button.
* @param string|null $payload Button payload.
* @param Intent $intent Intent of button.
*/
public function __construct(
string $text,
public ?string $payload = null,
public Intent $intent = Intent::Default,
) {
parent::__construct(ReplyButtonType::Message, $text);
}
}
@@ -0,0 +1,19 @@
<?php
declare(strict_types=1);
namespace BushlanovDev\MaxMessengerBot\Models\Attachments;
use BushlanovDev\MaxMessengerBot\Enums\AttachmentType;
use BushlanovDev\MaxMessengerBot\Models\Attachments\Payloads\ContactAttachmentPayload;
final readonly class ContactAttachment extends AbstractAttachment
{
/**
* @param ContactAttachmentPayload $payload Contact attachment payload.
*/
public function __construct(public ContactAttachmentPayload $payload)
{
parent::__construct(AttachmentType::Contact);
}
}
+21
View File
@@ -0,0 +1,21 @@
<?php
declare(strict_types=1);
namespace BushlanovDev\MaxMessengerBot\Models\Attachments;
use BushlanovDev\MaxMessengerBot\Enums\AttachmentType;
/**
* Represents an attachment containing a payload from a SendMessageButton.
*/
final readonly class DataAttachment extends AbstractAttachment
{
/**
* @param string $data The payload from the button.
*/
public function __construct(public string $data)
{
parent::__construct(AttachmentType::Data);
}
}
+24
View File
@@ -0,0 +1,24 @@
<?php
declare(strict_types=1);
namespace BushlanovDev\MaxMessengerBot\Models\Attachments;
use BushlanovDev\MaxMessengerBot\Enums\AttachmentType;
use BushlanovDev\MaxMessengerBot\Models\Attachments\Payloads\FileAttachmentPayload;
final readonly class FileAttachment extends AbstractAttachment
{
/**
* @param FileAttachmentPayload $payload File attachment payload.
* @param string $filename Uploaded file name.
* @param int $size File size in bytes.
*/
public function __construct(
public FileAttachmentPayload $payload,
public string $filename,
public int $size,
) {
parent::__construct(AttachmentType::File);
}
}
@@ -0,0 +1,19 @@
<?php
declare(strict_types=1);
namespace BushlanovDev\MaxMessengerBot\Models\Attachments;
use BushlanovDev\MaxMessengerBot\Enums\AttachmentType;
use BushlanovDev\MaxMessengerBot\Models\Attachments\Payloads\KeyboardPayload;
final readonly class InlineKeyboardAttachment extends AbstractAttachment
{
/**
* @param KeyboardPayload $payload Keyboard payload.
*/
public function __construct(public KeyboardPayload $payload)
{
parent::__construct(AttachmentType::InlineKeyboard);
}
}
@@ -0,0 +1,21 @@
<?php
declare(strict_types=1);
namespace BushlanovDev\MaxMessengerBot\Models\Attachments;
use BushlanovDev\MaxMessengerBot\Enums\AttachmentType;
final readonly class LocationAttachment extends AbstractAttachment
{
/**
* @param float $latitude
* @param float $longitude
*/
public function __construct(
public float $latitude,
public float $longitude,
) {
parent::__construct(AttachmentType::Location);
}
}
@@ -0,0 +1,24 @@
<?php
declare(strict_types=1);
namespace BushlanovDev\MaxMessengerBot\Models\Attachments\Payloads;
use BushlanovDev\MaxMessengerBot\Models\AbstractModel;
use BushlanovDev\MaxMessengerBot\Models\User;
/**
* Payload of a contact attachment.
*/
final readonly class ContactAttachmentPayload extends AbstractModel
{
/**
* @param string|null $vcfInfo User info in VCF format.
* @param User|null $maxInfo User info if the contact is a Max user.
*/
public function __construct(
public ?string $vcfInfo,
public ?User $maxInfo,
) {
}
}
@@ -0,0 +1,23 @@
<?php
declare(strict_types=1);
namespace BushlanovDev\MaxMessengerBot\Models\Attachments\Payloads;
use BushlanovDev\MaxMessengerBot\Models\AbstractModel;
/**
* Payload for a file attachment.
*/
final readonly class FileAttachmentPayload extends AbstractModel
{
/**
* @param string $url Media attachment URL.
* @param string $token Token to reuse the same attachment in other messages.
*/
public function __construct(
public string $url,
public string $token,
) {
}
}
@@ -4,12 +4,12 @@ declare(strict_types=1);
namespace BushlanovDev\MaxMessengerBot\Models\Attachments\Payloads;
use BushlanovDev\MaxMessengerBot\Models\Attachments\Buttons\AbstractButton;
use BushlanovDev\MaxMessengerBot\Models\Attachments\Buttons\Inline\AbstractInlineButton;
final readonly class InlineKeyboardAttachmentRequestPayload extends AbstractAttachmentRequestPayload
{
/**
* @param AbstractButton[][] $buttons
* @param AbstractInlineButton[][] $buttons
*/
public function __construct(
public array $buttons,
@@ -0,0 +1,21 @@
<?php
declare(strict_types=1);
namespace BushlanovDev\MaxMessengerBot\Models\Attachments\Payloads;
use BushlanovDev\MaxMessengerBot\Models\AbstractModel;
use BushlanovDev\MaxMessengerBot\Models\Attachments\Buttons\Inline\AbstractInlineButton;
/**
* Represents an inline keyboard structure.
*/
final readonly class KeyboardPayload extends AbstractModel
{
/**
* @param AbstractInlineButton[][] $buttons Two-dimensional array of buttons.
*/
public function __construct(public array $buttons)
{
}
}
@@ -0,0 +1,23 @@
<?php
declare(strict_types=1);
namespace BushlanovDev\MaxMessengerBot\Models\Attachments\Payloads;
use BushlanovDev\MaxMessengerBot\Models\AbstractModel;
/**
* Payload for media attachments like audio or video.
*/
final readonly class MediaAttachmentPayload extends AbstractModel
{
/**
* @param string $url Media attachment URL.
* @param string $token Token to reuse the same attachment in other messages.
*/
public function __construct(
public string $url,
public string $token,
) {
}
}
@@ -0,0 +1,25 @@
<?php
declare(strict_types=1);
namespace BushlanovDev\MaxMessengerBot\Models\Attachments\Payloads;
use BushlanovDev\MaxMessengerBot\Models\AbstractModel;
/**
* Payload for a photo attachment.
*/
final readonly class PhotoAttachmentPayload extends AbstractModel
{
/**
* @param string $url Media attachment URL.
* @param string $token Token to reuse the same attachment in other messages.
* @param int $photoId Unique identifier of this image.
*/
public function __construct(
public string $url,
public string $token,
public int $photoId,
) {
}
}
@@ -14,9 +14,7 @@ final readonly class PhotoToken extends AbstractModel
/**
* @param string $token Encoded information of uploaded image.
*/
public function __construct(
public string $token,
) {
public function __construct(public string $token)
{
}
}
@@ -0,0 +1,22 @@
<?php
declare(strict_types=1);
namespace BushlanovDev\MaxMessengerBot\Models\Attachments\Payloads;
use BushlanovDev\MaxMessengerBot\Models\Attachments\Buttons\Reply\AbstractReplyButton;
final readonly class ReplyKeyboardAttachmentRequestPayload extends AbstractAttachmentRequestPayload
{
/**
* @param AbstractReplyButton[][] $buttons Two-dimensional array of buttons.
* @param bool $direct Applicable only for chats.
* @param int|null $directUserId If set, reply keyboard will only be shown to this participant.
*/
public function __construct(
public array $buttons,
public bool $direct = false,
public ?int $directUserId = null,
) {
}
}
@@ -0,0 +1,23 @@
<?php
declare(strict_types=1);
namespace BushlanovDev\MaxMessengerBot\Models\Attachments\Payloads;
use BushlanovDev\MaxMessengerBot\Models\AbstractModel;
/**
* Payload for a sticker attachment.
*/
final readonly class StickerAttachmentPayload extends AbstractModel
{
/**
* @param string $url Media attachment URL.
* @param string $code Sticker identifier.
*/
public function __construct(
public string $url,
public string $code,
) {
}
}
@@ -1,19 +1,18 @@
<?php
declare(strict_types=1);
namespace BushlanovDev\MaxMessengerBot\Models\Attachments\Payloads;
/**
* Payload for attachments that are uploaded to the server first (video, audio, file).
*/
final readonly class UploadedInfoAttachmentRequestPayload extends AbstractAttachmentRequestPayload
{
/**
* @param string $token The unique token received after a successful file upload.
*/
public function __construct(
public string $token,
) {
}
}
<?php
declare(strict_types=1);
namespace BushlanovDev\MaxMessengerBot\Models\Attachments\Payloads;
/**
* Payload for attachments that are uploaded to the server first (video, audio, file).
*/
final readonly class UploadedInfoAttachmentRequestPayload extends AbstractAttachmentRequestPayload
{
/**
* @param string $token The unique token received after a successful file upload.
*/
public function __construct(public string $token)
{
}
}
@@ -0,0 +1,20 @@
<?php
declare(strict_types=1);
namespace BushlanovDev\MaxMessengerBot\Models\Attachments\Payloads;
use BushlanovDev\MaxMessengerBot\Models\AbstractModel;
/**
* Represents a video thumbnail image.
*/
final readonly class VideoThumbnail extends AbstractModel
{
/**
* @param string $url Media attachment URL.
*/
public function __construct(public string $url)
{
}
}
@@ -0,0 +1,19 @@
<?php
declare(strict_types=1);
namespace BushlanovDev\MaxMessengerBot\Models\Attachments;
use BushlanovDev\MaxMessengerBot\Enums\AttachmentType;
use BushlanovDev\MaxMessengerBot\Models\Attachments\Payloads\PhotoAttachmentPayload;
final readonly class PhotoAttachment extends AbstractAttachment
{
/**
* @param PhotoAttachmentPayload $payload Photo attachment payload.
*/
public function __construct(public PhotoAttachmentPayload $payload)
{
parent::__construct(AttachmentType::Image);
}
}
@@ -0,0 +1,19 @@
<?php
declare(strict_types=1);
namespace BushlanovDev\MaxMessengerBot\Models\Attachments;
use BushlanovDev\MaxMessengerBot\Enums\AttachmentType;
use BushlanovDev\MaxMessengerBot\Models\Attachments\Buttons\Reply\AbstractReplyButton;
final readonly class ReplyKeyboardAttachment extends AbstractAttachment
{
/**
* @param AbstractReplyButton[][] $buttons
*/
public function __construct(public array $buttons)
{
parent::__construct(AttachmentType::ReplyKeyboard);
}
}
@@ -5,13 +5,13 @@ declare(strict_types=1);
namespace BushlanovDev\MaxMessengerBot\Models\Attachments\Requests;
use BushlanovDev\MaxMessengerBot\Enums\AttachmentType;
use BushlanovDev\MaxMessengerBot\Models\Attachments\Buttons\AbstractButton;
use BushlanovDev\MaxMessengerBot\Models\Attachments\Buttons\Inline\AbstractInlineButton;
use BushlanovDev\MaxMessengerBot\Models\Attachments\Payloads\InlineKeyboardAttachmentRequestPayload;
final readonly class InlineKeyboardAttachmentRequest extends AbstractAttachmentRequest
{
/**
* @param AbstractButton[][] $buttons
* @param AbstractInlineButton[][] $buttons
*/
public function __construct(array $buttons)
{
@@ -0,0 +1,28 @@
<?php
declare(strict_types=1);
namespace BushlanovDev\MaxMessengerBot\Models\Attachments\Requests;
use BushlanovDev\MaxMessengerBot\Enums\AttachmentType;
use BushlanovDev\MaxMessengerBot\Models\Attachments\Buttons\Reply\AbstractReplyButton;
use BushlanovDev\MaxMessengerBot\Models\Attachments\Payloads\ReplyKeyboardAttachmentRequestPayload;
final readonly class ReplyKeyboardAttachmentRequest extends AbstractAttachmentRequest
{
/**
* @param AbstractReplyButton[][] $buttons
* @param bool $direct
* @param int|null $directUserId
*/
public function __construct(
array $buttons,
bool $direct = false,
?int $directUserId = null
) {
parent::__construct(
AttachmentType::ReplyKeyboard,
new ReplyKeyboardAttachmentRequestPayload($buttons, $direct, $directUserId),
);
}
}
@@ -0,0 +1,23 @@
<?php
declare(strict_types=1);
namespace BushlanovDev\MaxMessengerBot\Models\Attachments;
use BushlanovDev\MaxMessengerBot\Enums\AttachmentType;
use BushlanovDev\MaxMessengerBot\Models\Attachments\Payloads\ShareAttachmentRequestPayload;
/**
* Represents a share (URL preview) attachment.
*/
final readonly class ShareAttachment extends AbstractAttachment
{
public function __construct(
public ShareAttachmentRequestPayload $payload,
public ?string $title,
public ?string $description,
public ?string $imageUrl,
) {
parent::__construct(AttachmentType::Share);
}
}
@@ -0,0 +1,24 @@
<?php
declare(strict_types=1);
namespace BushlanovDev\MaxMessengerBot\Models\Attachments;
use BushlanovDev\MaxMessengerBot\Enums\AttachmentType;
use BushlanovDev\MaxMessengerBot\Models\Attachments\Payloads\StickerAttachmentPayload;
final readonly class StickerAttachment extends AbstractAttachment
{
/**
* @param StickerAttachmentPayload $payload Sticker attachment payload.
* @param int $width
* @param int $height
*/
public function __construct(
public StickerAttachmentPayload $payload,
public int $width,
public int $height,
) {
parent::__construct(AttachmentType::Sticker);
}
}
@@ -0,0 +1,29 @@
<?php
declare(strict_types=1);
namespace BushlanovDev\MaxMessengerBot\Models\Attachments;
use BushlanovDev\MaxMessengerBot\Enums\AttachmentType;
use BushlanovDev\MaxMessengerBot\Models\Attachments\Payloads\MediaAttachmentPayload;
use BushlanovDev\MaxMessengerBot\Models\Attachments\Payloads\VideoThumbnail;
final readonly class VideoAttachment extends AbstractAttachment
{
/**
* @param MediaAttachmentPayload $payload Video attachment payload.
* @param VideoThumbnail|null $thumbnail Video thumbnail.
* @param int|null $width Video width.
* @param int|null $height Video height.
* @param int|null $duration Video duration in seconds.
*/
public function __construct(
public MediaAttachmentPayload $payload,
public ?VideoThumbnail $thumbnail,
public ?int $width,
public ?int $height,
public ?int $duration,
) {
parent::__construct(AttachmentType::Video);
}
}
+21
View File
@@ -0,0 +1,21 @@
<?php
declare(strict_types=1);
namespace BushlanovDev\MaxMessengerBot\Models;
use BushlanovDev\MaxMessengerBot\Models\Attachments\Payloads\PhotoAttachmentRequestPayload;
/**
* Represents the data to patch for a bot. Instantiate with named arguments.
*
* Example: new BotPatch(name: 'New Bot Name', description: null);
*
* @property-read string|null $name
* @property-read string|null $description
* @property-read BotCommand[]|null $commands
* @property-read PhotoAttachmentRequestPayload|null $photo
*/
final readonly class BotPatch extends AbstractPatchModel
{
}
+2 -2
View File
@@ -24,7 +24,7 @@ final readonly class Chat extends AbstractModel
* @param int|null $ownerId Identifier of chat owner. Visible only for chat admins
* @param string|null $link Link on chat.
* @param string|null $description Chat description.
* @param User|null $dialogWithUser Another user in conversation. For `dialog` type chats only.
* @param UserWithPhoto|null $dialogWithUser Another user in conversation. For `dialog` type chats only.
* @param int|null $messagesCount Messages count in chat. Only for group chats and channels. Not available for dialogs.
* @param string|null $chatMessageId Identifier of message that contains `chat` button initialized chat.
* @param Message|null $pinnedMessage Pinned message in chat or channel. Returned only when single chat is requested.
@@ -41,7 +41,7 @@ final readonly class Chat extends AbstractModel
public ?int $ownerId,
public ?string $link,
public ?string $description,
public ?User $dialogWithUser,
public ?UserWithPhoto $dialogWithUser,
public ?int $messagesCount,
public ?string $chatMessageId,
public ?Message $pinnedMessage,
+25
View File
@@ -0,0 +1,25 @@
<?php
declare(strict_types=1);
namespace BushlanovDev\MaxMessengerBot\Models;
use BushlanovDev\MaxMessengerBot\Attributes\ArrayOf;
use BushlanovDev\MaxMessengerBot\Enums\ChatAdminPermission;
/**
* Represents an administrator to be set in a chat, linking a user ID with their permissions.
*/
final readonly class ChatAdmin extends AbstractModel
{
/**
* @param int $userId The identifier of the user to be made an admin.
* @param ChatAdminPermission[] $permissions The list of permissions to grant to the user.
*/
public function __construct(
public int $userId,
#[ArrayOf(ChatAdminPermission::class)]
public array $permissions,
) {
}
}
+49
View File
@@ -0,0 +1,49 @@
<?php
declare(strict_types=1);
namespace BushlanovDev\MaxMessengerBot\Models;
use BushlanovDev\MaxMessengerBot\Attributes\ArrayOf;
use BushlanovDev\MaxMessengerBot\Enums\ChatAdminPermission;
/**
* Represents a member of a chat, including their user information and chat-specific status.
*/
final readonly class ChatMember extends AbstractModel
{
/**
* @param int $userId User's identifier.
* @param string $firstName User's first name.
* @param string|null $lastName User's last name.
* @param string|null $username User's public username.
* @param bool $isBot True if the user is a bot.
* @param int $lastActivityTime Time of the user's last activity in Max.
* @param string|null $description User's profile description.
* @param string|null $avatarUrl URL of the user's avatar.
* @param string|null $fullAvatarUrl URL of the user's full-sized avatar.
* @param int $lastAccessTime The time the user last accessed the chat.
* @param bool $isOwner True if this member is the owner of the chat.
* @param bool $isAdmin True if this member is an administrator of the chat.
* @param int $joinTime The time the user joined the chat.
* @param ChatAdminPermission[]|null $permissions A list of permissions if the member is an admin, otherwise null.
*/
public function __construct(
public int $userId,
public string $firstName,
public ?string $lastName,
public ?string $username,
public bool $isBot,
public int $lastActivityTime,
public ?string $description,
public ?string $avatarUrl,
public ?string $fullAvatarUrl,
public int $lastAccessTime,
public bool $isOwner,
public bool $isAdmin,
public int $joinTime,
#[ArrayOf(ChatAdminPermission::class)]
public ?array $permissions,
) {
}
}
+24
View File
@@ -0,0 +1,24 @@
<?php
declare(strict_types=1);
namespace BushlanovDev\MaxMessengerBot\Models;
use BushlanovDev\MaxMessengerBot\Attributes\ArrayOf;
/**
* Represents a paginated list of chat members.
*/
final readonly class ChatMembersList extends AbstractModel
{
/**
* @param ChatMember[] $members A list of chat members.
* @param int|null $marker A pointer to the next page of data. Null if this is the last page.
*/
public function __construct(
#[ArrayOf(ChatMember::class)]
public array $members,
public ?int $marker,
) {
}
}
+21
View File
@@ -0,0 +1,21 @@
<?php
declare(strict_types=1);
namespace BushlanovDev\MaxMessengerBot\Models;
use BushlanovDev\MaxMessengerBot\Models\Attachments\Payloads\PhotoAttachmentRequestPayload;
/**
* Represents the data to patch for a chat. Instantiate with named arguments.
*
* Example: new ChatPatch(title: 'New Chat Title');
*
* @property-read PhotoAttachmentRequestPayload|null $icon
* @property-read string|null $title
* @property-read string|null $pin Message ID to be pinned.
* @property-read bool|null $notify
*/
final readonly class ChatPatch extends AbstractPatchModel
{
}
+2 -3
View File
@@ -9,8 +9,7 @@ final readonly class Image extends AbstractModel
/**
* @param string $url URL of image.
*/
public function __construct(
public string $url,
) {
public function __construct(public string $url)
{
}
}
+27
View File
@@ -0,0 +1,27 @@
<?php
declare(strict_types=1);
namespace BushlanovDev\MaxMessengerBot\Models;
use BushlanovDev\MaxMessengerBot\Enums\MessageLinkType;
/**
* Represents a forwarded or replied message linked to the main message.
*/
final readonly class LinkedMessage extends AbstractModel
{
/**
* @param MessageLinkType $type Type of linked message (forward or reply).
* @param MessageBody $message The body of the original message.
* @param User|null $sender The sender of the original message. Can be null if posted on behalf of a channel.
* @param int|null $chatId The chat where the message was originally posted (for forwarded messages).
*/
public function __construct(
public MessageLinkType $type,
public MessageBody $message,
public ?User $sender,
public ?int $chatId,
) {
}
}
+26
View File
@@ -0,0 +1,26 @@
<?php
declare(strict_types=1);
namespace BushlanovDev\MaxMessengerBot\Models\Markup;
use BushlanovDev\MaxMessengerBot\Enums\MarkupType;
use BushlanovDev\MaxMessengerBot\Models\AbstractModel;
/**
* Base class for a text markup element.
*/
abstract readonly class AbstractMarkup extends AbstractModel
{
/**
* @param MarkupType $type The type of the markup element.
* @param int $from Element start index (zero-based) in text.
* @param int $length Length of the markup element.
*/
public function __construct(
public MarkupType $type,
public int $from,
public int $length,
) {
}
}
+24
View File
@@ -0,0 +1,24 @@
<?php
declare(strict_types=1);
namespace BushlanovDev\MaxMessengerBot\Models\Markup;
use BushlanovDev\MaxMessengerBot\Enums\MarkupType;
/**
* Represents an *emphasized* (italic) part of the text.
*/
final readonly class EmphasizedMarkup extends AbstractMarkup
{
/**
* @param int $from Element start index (zero-based) in text.
* @param int $length Length of the markup element.
*/
public function __construct(
int $from,
int $length,
) {
parent::__construct(MarkupType::Emphasized, $from, $length);
}
}
+24
View File
@@ -0,0 +1,24 @@
<?php
declare(strict_types=1);
namespace BushlanovDev\MaxMessengerBot\Models\Markup;
use BushlanovDev\MaxMessengerBot\Enums\MarkupType;
/**
* Represents a # header part of the text.
*/
final readonly class HeadingMarkup extends AbstractMarkup
{
/**
* @param int $from Element start index (zero-based) in text.
* @param int $length Length of the markup element.
*/
public function __construct(
int $from,
int $length,
) {
parent::__construct(MarkupType::Heading, $from, $length);
}
}
+24
View File
@@ -0,0 +1,24 @@
<?php
declare(strict_types=1);
namespace BushlanovDev\MaxMessengerBot\Models\Markup;
use BushlanovDev\MaxMessengerBot\Enums\MarkupType;
/**
* Represents a ^^highlighted^^ part of the text.
*/
final readonly class HighlightedMarkup extends AbstractMarkup
{
/**
* @param int $from Element start index (zero-based) in text.
* @param int $length Length of the markup element.
*/
public function __construct(
int $from,
int $length,
) {
parent::__construct(MarkupType::Highlighted, $from, $length);
}
}
+26
View File
@@ -0,0 +1,26 @@
<?php
declare(strict_types=1);
namespace BushlanovDev\MaxMessengerBot\Models\Markup;
use BushlanovDev\MaxMessengerBot\Enums\MarkupType;
/**
* Represents a link in the text.
*/
final readonly class LinkMarkup extends AbstractMarkup
{
/**
* @param int $from Element start index (zero-based) in text.
* @param int $length Length of the markup element.
* @param string $url Link's URL.
*/
public function __construct(
int $from,
int $length,
public string $url,
) {
parent::__construct(MarkupType::Link, $from, $length);
}
}
+24
View File
@@ -0,0 +1,24 @@
<?php
declare(strict_types=1);
namespace BushlanovDev\MaxMessengerBot\Models\Markup;
use BushlanovDev\MaxMessengerBot\Enums\MarkupType;
/**
* Represents a `monospaced` part of the text.
*/
final readonly class MonospacedMarkup extends AbstractMarkup
{
/**
* @param int $from Element start index (zero-based) in text.
* @param int $length Length of the markup element.
*/
public function __construct(
int $from,
int $length,
) {
parent::__construct(MarkupType::Monospaced, $from, $length);
}
}
+24
View File
@@ -0,0 +1,24 @@
<?php
declare(strict_types=1);
namespace BushlanovDev\MaxMessengerBot\Models\Markup;
use BushlanovDev\MaxMessengerBot\Enums\MarkupType;
/**
* Represents a ~strikethrough~ part of the text.
*/
final readonly class StrikethroughMarkup extends AbstractMarkup
{
/**
* @param int $from Element start index (zero-based) in text.
* @param int $length Length of the markup element.
*/
public function __construct(
int $from,
int $length,
) {
parent::__construct(MarkupType::Strikethrough, $from, $length);
}
}
+24
View File
@@ -0,0 +1,24 @@
<?php
declare(strict_types=1);
namespace BushlanovDev\MaxMessengerBot\Models\Markup;
use BushlanovDev\MaxMessengerBot\Enums\MarkupType;
/**
* Represents a **strong** (bold) part of the text.
*/
final readonly class StrongMarkup extends AbstractMarkup
{
/**
* @param int $from Element start index (zero-based) in text.
* @param int $length Length of the markup element.
*/
public function __construct(
int $from,
int $length,
) {
parent::__construct(MarkupType::Strong, $from, $length);
}
}
+24
View File
@@ -0,0 +1,24 @@
<?php
declare(strict_types=1);
namespace BushlanovDev\MaxMessengerBot\Models\Markup;
use BushlanovDev\MaxMessengerBot\Enums\MarkupType;
/**
* Represents an ++underlined++ part of the text.
*/
final readonly class UnderlineMarkup extends AbstractMarkup
{
/**
* @param int $from Element start index (zero-based) in text.
* @param int $length Length of the markup element.
*/
public function __construct(
int $from,
int $length,
) {
parent::__construct(MarkupType::Underline, $from, $length);
}
}
+28
View File
@@ -0,0 +1,28 @@
<?php
declare(strict_types=1);
namespace BushlanovDev\MaxMessengerBot\Models\Markup;
use BushlanovDev\MaxMessengerBot\Enums\MarkupType;
/**
* Represents a user mention in the text.
*/
final readonly class UserMentionMarkup extends AbstractMarkup
{
/**
* @param int $from Element start index (zero-based) in text.
* @param int $length Length of the markup element.
* @param string|null $userLink "@username" of the mentioned user.
* @param int|null $userId Identifier of the mentioned user without a username.
*/
public function __construct(
int $from,
int $length,
public ?string $userLink,
public ?int $userId,
) {
parent::__construct(MarkupType::UserMention, $from, $length);
}
}
+8 -4
View File
@@ -11,17 +11,21 @@ final readonly class Message extends AbstractModel
{
/**
* @param int $timestamp Unix-time when message was created.
* @param MessageBody $body Body of created message. Text + attachments.
* @param Recipient $recipient Message recipient. Could be user or chat.
* @param Sender|null $sender User who sent this message. Can be null if message has been posted on behalf of a channel.
* @param MessageBody|null $body Body of created message. Text + attachments.
* @param User|null $sender User who sent this message. Can be null if message has been posted on behalf of a channel.
* @param string|null $url Message public URL. Can be null for dialogs or non-public chats/channels.
* @param LinkedMessage|null $link Forwarded or replied message.
* @param MessageStat|null $stat Message statistics. Available only for channels.
*/
public function __construct(
public int $timestamp,
public MessageBody $body,
public Recipient $recipient,
public ?Sender $sender,
public ?MessageBody $body,
public ?User $sender,
public ?string $url,
public ?LinkedMessage $link,
public ?MessageStat $stat,
) {
}
}
+7
View File
@@ -4,6 +4,9 @@ declare(strict_types=1);
namespace BushlanovDev\MaxMessengerBot\Models;
use BushlanovDev\MaxMessengerBot\Models\Attachments\AbstractAttachment;
use BushlanovDev\MaxMessengerBot\Models\Markup\AbstractMarkup;
/**
* Body of created message. Text + attachments.
*/
@@ -13,11 +16,15 @@ final readonly class MessageBody extends AbstractModel
* @param string $mid Unique identifier of message.
* @param int $seq Sequence identifier of message in chat.
* @param string|null $text Message text.
* @param AbstractAttachment[]|null $attachments Message attachments.
* @param AbstractMarkup[]|null $markup Message text markup.
*/
public function __construct(
public string $mid,
public int $seq,
public ?string $text,
public ?array $attachments,
public ?array $markup,
) {
}
}
+18
View File
@@ -0,0 +1,18 @@
<?php
declare(strict_types=1);
namespace BushlanovDev\MaxMessengerBot\Models;
/**
* Message statistics.
*/
final readonly class MessageStat extends AbstractModel
{
/**
* @param int $views Number of views.
*/
public function __construct(public int $views)
{
}
}
+2 -7
View File
@@ -11,11 +11,9 @@ final readonly class User extends AbstractModel
* @param string $firstName Users first name.
* @param string|null $lastName Users last name.
* @param string|null $username Unique public user name. Can be `null` if user is not accessible or it is not set.
* @param bool $isBot `true` if user is bot.
* @param bool $isBot Is the user a bot.
* @param int $lastActivityTime Time of last user activity in Max (Unix timestamp in milliseconds).
* @param string|null $description User description. Can be `null` if user did not fill it out.
* @param string|null $avatarUrl URL of avatar.
* @param string|null $fullAvatarUrl URL of avatar of a bigger size.
* Can be outdated if user disabled its "online" status in settings.
*/
public function __construct(
public int $userId,
@@ -24,9 +22,6 @@ final readonly class User extends AbstractModel
public ?string $username,
public bool $isBot,
public int $lastActivityTime,
public ?string $description,
public ?string $avatarUrl,
public ?string $fullAvatarUrl,
) {
}
}
@@ -4,18 +4,18 @@ declare(strict_types=1);
namespace BushlanovDev\MaxMessengerBot\Models;
/**
* User who sent this message.
*/
final readonly class Sender extends AbstractModel
final readonly class UserWithPhoto extends AbstractModel
{
/**
* @param int $userId Users identifier.
* @param string $firstName Users first name.
* @param string|null $lastName Users last name.
* @param string|null $username Unique public user name. Can be null if user is not accessible or it is not set.
* @param bool $isBot Is the user a bot.
* @param int $lastActivityTime Time of last user activity in Max (Unix timestamp in milliseconds). Can be outdated if user disabled its "online" status in settings.
* @param string|null $username Unique public user name. Can be `null` if user is not accessible or it is not set.
* @param bool $isBot `true` if user is bot.
* @param int $lastActivityTime Time of last user activity in Max (Unix timestamp in milliseconds).
* @param string|null $description UserWithPhoto description. Can be `null` if user did not fill it out.
* @param string|null $avatarUrl URL of avatar.
* @param string|null $fullAvatarUrl URL of avatar of a bigger size.
*/
public function __construct(
public int $userId,
@@ -24,6 +24,9 @@ final readonly class Sender extends AbstractModel
public ?string $username,
public bool $isBot,
public int $lastActivityTime,
public ?string $description,
public ?string $avatarUrl,
public ?string $fullAvatarUrl,
) {
}
}
+31
View File
@@ -0,0 +1,31 @@
<?php
declare(strict_types=1);
namespace BushlanovDev\MaxMessengerBot\Models;
use BushlanovDev\MaxMessengerBot\Models\Attachments\Payloads\PhotoAttachmentRequestPayload;
/**
* Contains detailed information about a video attachment.
*/
final readonly class VideoAttachmentDetails extends AbstractModel
{
/**
* @param string $token The video attachment token.
* @param int $width The width of the video in pixels.
* @param int $height The height of the video in pixels.
* @param int $duration The duration of the video in seconds.
* @param VideoUrls|null $urls URLs to download or play the video. Can be null if the video is unavailable.
* @param PhotoAttachmentRequestPayload|null $thumbnail The video's thumbnail image information.
*/
public function __construct(
public string $token,
public int $width,
public int $height,
public int $duration,
public ?VideoUrls $urls = null,
public ?PhotoAttachmentRequestPayload $thumbnail = null,
) {
}
}
+31
View File
@@ -0,0 +1,31 @@
<?php
declare(strict_types=1);
namespace BushlanovDev\MaxMessengerBot\Models;
/**
* Contains URLs for a video attachment in various resolutions.
*/
final readonly class VideoUrls extends AbstractModel
{
/**
* @param string|null $mp4_1080 Video URL in 1080p resolution, if available.
* @param string|null $mp4_720 Video URL in 720p resolution, if available.
* @param string|null $mp4_480 Video URL in 480p resolution, if available.
* @param string|null $mp4_360 Video URL in 360p resolution, if available.
* @param string|null $mp4_240 Video URL in 240p resolution, if available.
* @param string|null $mp4_144 Video URL in 144p resolution, if available.
* @param string|null $hls Live streaming URL (HLS), if available.
*/
public function __construct(
public ?string $mp4_1080 = null,
public ?string $mp4_720 = null,
public ?string $mp4_480 = null,
public ?string $mp4_360 = null,
public ?string $mp4_240 = null,
public ?string $mp4_144 = null,
public ?string $hls = null,
) {
}
}
+231
View File
@@ -0,0 +1,231 @@
<?php
declare(strict_types=1);
namespace BushlanovDev\MaxMessengerBot;
use BushlanovDev\MaxMessengerBot\Enums\UpdateType;
use BushlanovDev\MaxMessengerBot\Models\Updates\AbstractUpdate;
use BushlanovDev\MaxMessengerBot\Models\Updates\MessageCreatedUpdate;
/**
* Dispatches updates to registered handlers. Supports handling specific update types and text commands.
*/
final class UpdateDispatcher
{
/**
* @var array<string, callable>
*/
private array $handlers = [];
/**
* @var array<string, callable>
*/
private array $commandHandlers = [];
/**
* @param Api $api
*/
public function __construct(private readonly Api $api)
{
}
/**
* Registers a handler for a specific update type.
*
* @param UpdateType $type The type of update to handle.
* @param callable $handler The function to execute when the update is received.
*
* @return $this
*/
public function addHandler(UpdateType $type, callable $handler): self
{
$this->handlers[$type->value] = $handler;
return $this;
}
/**
* Registers a handler for a text command without a command prefix "/" (e.g., "start").
* The command must be the first word in a message.
*
* @param string $command The command string (e.g., "start").
* @param callable(MessageCreatedUpdate, Api): void $handler The handler to execute.
*
* @return $this
*/
public function onCommand(string $command, callable $handler): self
{
$this->commandHandlers[$command] = $handler;
return $this;
}
/**
* Dispatches a parsed Update object to its registered handler.
* Command handlers are prioritized over generic message handlers.
*
* @param AbstractUpdate $update The update object to dispatch.
*/
public function dispatch(AbstractUpdate $update): void
{
if ($update instanceof MessageCreatedUpdate && $update->message->body?->text) {
$text = $update->message->body->text;
$parts = explode(' ', trim($text));
$command = $parts[0];
if (isset($this->commandHandlers[$command])) {
$this->commandHandlers[$command]($update, $this->api);
return;
}
}
$handler = $this->handlers[$update->updateType->value] ?? null;
if ($handler) {
$handler($update, $this->api);
}
}
/**
* A convenient alias for addHandler(UpdateType::MessageCreated, $handler).
*
* @param callable(Models\Updates\MessageCreatedUpdate, Api): void $handler
*
* @return $this
* @codeCoverageIgnore
*/
public function onMessageCreated(callable $handler): self
{
return $this->addHandler(UpdateType::MessageCreated, $handler);
}
/**
* A convenient alias for addHandler(UpdateType::MessageCallback, $handler).
*
* @param callable(Models\Updates\MessageCallbackUpdate, Api): void $handler
*
* @return $this
* @codeCoverageIgnore
*/
public function onMessageCallback(callable $handler): self
{
return $this->addHandler(UpdateType::MessageCallback, $handler);
}
/**
* A convenient alias for addHandler(UpdateType::MessageEdited, $handler).
*
* @param callable(Models\Updates\MessageEditedUpdate, Api): void $handler
*
* @return $this
* @codeCoverageIgnore
*/
public function onMessageEdited(callable $handler): self
{
return $this->addHandler(UpdateType::MessageEdited, $handler);
}
/**
* A convenient alias for addHandler(UpdateType::MessageRemoved, $handler).
*
* @param callable(Models\Updates\MessageRemovedUpdate, Api): void $handler
*
* @return $this
* @codeCoverageIgnore
*/
public function onMessageRemoved(callable $handler): self
{
return $this->addHandler(UpdateType::MessageRemoved, $handler);
}
/**
* A convenient alias for addHandler(UpdateType::BotAdded, $handler).
*
* @param callable(Models\Updates\BotAddedToChatUpdate, Api): void $handler
*
* @return $this
* @codeCoverageIgnore
*/
public function onBotAdded(callable $handler): self
{
return $this->addHandler(UpdateType::BotAdded, $handler);
}
/**
* A convenient alias for addHandler(UpdateType::BotRemoved, $handler).
*
* @param callable(Models\Updates\BotRemovedFromChatUpdate, Api): void $handler
*
* @return $this
* @codeCoverageIgnore
*/
public function onBotRemoved(callable $handler): self
{
return $this->addHandler(UpdateType::BotRemoved, $handler);
}
/**
* A convenient alias for addHandler(UpdateType::UserAdded, $handler).
*
* @param callable(Models\Updates\UserAddedToChatUpdate, Api): void $handler
*
* @return $this
* @codeCoverageIgnore
*/
public function onUserAdded(callable $handler): self
{
return $this->addHandler(UpdateType::UserAdded, $handler);
}
/**
* A convenient alias for addHandler(UpdateType::UserRemoved, $handler).
*
* @param callable(Models\Updates\UserRemovedFromChatUpdate, Api): void $handler
*
* @return $this
* @codeCoverageIgnore
*/
public function onUserRemoved(callable $handler): self
{
return $this->addHandler(UpdateType::UserRemoved, $handler);
}
/**
* A convenient alias for addHandler(UpdateType::BotStarted, $handler).
*
* @param callable(Models\Updates\BotStartedUpdate, Api): void $handler
*
* @return $this
* @codeCoverageIgnore
*/
public function onBotStarted(callable $handler): self
{
return $this->addHandler(UpdateType::BotStarted, $handler);
}
/**
* A convenient alias for addHandler(UpdateType::ChatTitleChanged, $handler).
*
* @param callable(Models\Updates\ChatTitleChangedUpdate, Api): void $handler
*
* @return $this
* @codeCoverageIgnore
*/
public function onChatTitleChanged(callable $handler): self
{
return $this->addHandler(UpdateType::ChatTitleChanged, $handler);
}
/**
* A convenient alias for addHandler(UpdateType::MessageChatCreated, $handler).
*
* @param callable(Models\Updates\MessageChatCreatedUpdate, Api): void $handler
*
* @return $this
* @codeCoverageIgnore
*/
public function onMessageChatCreated(callable $handler): self
{
return $this->addHandler(UpdateType::MessageChatCreated, $handler);
}
}
+22 -226
View File
@@ -4,201 +4,37 @@ declare(strict_types=1);
namespace BushlanovDev\MaxMessengerBot;
use BushlanovDev\MaxMessengerBot\Enums\UpdateType;
use BushlanovDev\MaxMessengerBot\Exceptions\SecurityException;
use BushlanovDev\MaxMessengerBot\Exceptions\SerializationException;
use BushlanovDev\MaxMessengerBot\Models\Updates\AbstractUpdate;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Log\LoggerInterface;
/**
* A class designed to process incoming webhook requests from the Max API.
* It verifies the request's authenticity, parses it, and dispatches it
* to the appropriate registered event handler.
* It verifies the request's authenticity, parses it, and uses an UpdateDispatcher
* to route it to the appropriate handler.
*/
final class WebhookHandler
final readonly class WebhookHandler
{
/**
* @var array<string, callable>
*/
private array $handlers = [];
/**
* @param Api $api An instance of the Api to be passed to handlers for immediate responses.
* @param ModelFactory $modelFactory An instance of the model factory to create Update objects.
* @param string|null $secret The secret key provided during webhook subscription to verify requests.
* @param UpdateDispatcher $dispatcher The update dispatcher.
* @param ModelFactory $modelFactory The model factory.
* @param LoggerInterface $logger PSR LoggerInterface.
* @param string|null $secret The secret key for request verification.
*/
public function __construct(
private readonly Api $api,
private readonly ModelFactory $modelFactory,
private readonly ?string $secret = null,
private UpdateDispatcher $dispatcher,
private ModelFactory $modelFactory,
private LoggerInterface $logger,
private ?string $secret,
) {
}
/**
* Registers a handler for a specific update type.
*
* @param UpdateType $type The type of update to handle.
* @param callable $handler The function to execute when the update is received.
* The handler will receive the specific Update object (e.g., MessageCreatedUpdate) and the Api instance.
*
* @return WebhookHandler
*/
public function addHandler(UpdateType $type, callable $handler): self
{
$this->handlers[$type->value] = $handler;
return $this;
}
/**
* A convenient alias for addHandler(UpdateType::MessageCreated, $handler).
*
* @param callable(Models\Updates\MessageCreatedUpdate, Api): void $handler
*
* @return WebhookHandler
*/
public function onMessageCreated(callable $handler): self
{
return $this->addHandler(UpdateType::MessageCreated, $handler);
}
/**
* A convenient alias for addHandler(UpdateType::MessageCallback, $handler).
*
* @param callable(Models\Updates\MessageCallbackUpdate, Api): void $handler
*
* @return WebhookHandler
* @codeCoverageIgnore
*/
public function onMessageCallback(callable $handler): self
{
return $this->addHandler(UpdateType::MessageCallback, $handler);
}
/**
* A convenient alias for addHandler(UpdateType::MessageEdited, $handler).
*
* @param callable(Models\Updates\MessageEditedUpdate, Api): void $handler
*
* @return WebhookHandler
* @codeCoverageIgnore
*/
public function onMessageEdited(callable $handler): self
{
return $this->addHandler(UpdateType::MessageEdited, $handler);
}
/**
* A convenient alias for addHandler(UpdateType::MessageRemoved, $handler).
*
* @param callable(Models\Updates\MessageRemovedUpdate, Api): void $handler
*
* @return WebhookHandler
* @codeCoverageIgnore
*/
public function onMessageRemoved(callable $handler): self
{
return $this->addHandler(UpdateType::MessageRemoved, $handler);
}
/**
* A convenient alias for addHandler(UpdateType::BotAdded, $handler).
*
* @param callable(Models\Updates\BotAddedToChatUpdate, Api): void $handler
*
* @return WebhookHandler
* @codeCoverageIgnore
*/
public function onBotAdded(callable $handler): self
{
return $this->addHandler(UpdateType::BotAdded, $handler);
}
/**
* A convenient alias for addHandler(UpdateType::BotRemoved, $handler).
*
* @param callable(Models\Updates\BotRemovedFromChatUpdate, Api): void $handler
*
* @return WebhookHandler
* @codeCoverageIgnore
*/
public function onBotRemoved(callable $handler): self
{
return $this->addHandler(UpdateType::BotRemoved, $handler);
}
/**
* A convenient alias for addHandler(UpdateType::UserAdded, $handler).
*
* @param callable(Models\Updates\UserAddedToChatUpdate, Api): void $handler
*
* @return WebhookHandler
* @codeCoverageIgnore
*/
public function onUserAdded(callable $handler): self
{
return $this->addHandler(UpdateType::UserAdded, $handler);
}
/**
* A convenient alias for addHandler(UpdateType::UserRemoved, $handler).
*
* @param callable(Models\Updates\UserRemovedFromChatUpdate, Api): void $handler
*
* @return WebhookHandler
* @codeCoverageIgnore
*/
public function onUserRemoved(callable $handler): self
{
return $this->addHandler(UpdateType::UserRemoved, $handler);
}
/**
* A convenient alias for addHandler(UpdateType::BotStarted, $handler).
*
* @param callable(Models\Updates\BotStartedUpdate, Api): void $handler
*
* @return WebhookHandler
* @codeCoverageIgnore
*/
public function onBotStarted(callable $handler): self
{
return $this->addHandler(UpdateType::BotStarted, $handler);
}
/**
* A convenient alias for addHandler(UpdateType::ChatTitleChanged, $handler).
*
* @param callable(Models\Updates\ChatTitleChangedUpdate, Api): void $handler
*
* @return WebhookHandler
* @codeCoverageIgnore
*/
public function onChatTitleChanged(callable $handler): self
{
return $this->addHandler(UpdateType::ChatTitleChanged, $handler);
}
/**
* A convenient alias for addHandler(UpdateType::MessageChatCreated, $handler).
*
* @param callable(Models\Updates\MessageChatCreatedUpdate, Api): void $handler
*
* @return WebhookHandler
* @codeCoverageIgnore
*/
public function onMessageChatCreated(callable $handler): self
{
return $this->addHandler(UpdateType::MessageChatCreated, $handler);
}
/**
* Processes an incoming webhook request.
* This is the main entry point. It reads the HTTP request body and headers,
* verifies the signature, parses the update, and calls the appropriate handler.
* It automatically sends the correct HTTP response code.
* It reads the HTTP request, verifies, parses, and dispatches the update.
*
* @param ServerRequestInterface|null $request The Psr7 HTTP request to process.
* @param ServerRequestInterface|null $request The PSR-7 HTTP request. If null, created from globals.
*
* @throws \ReflectionException
* @throws SecurityException
@@ -206,24 +42,6 @@ final class WebhookHandler
* @throws \LogicException
*/
public function handle(?ServerRequestInterface $request = null): void
{
$this->dispatch($this->getUpdate($request));
http_response_code(200);
}
/**
* Parses the raw request data and returns a typed Update object.
*
* @param ServerRequestInterface|null $request The Psr7 HTTP request to process.
*
* @return AbstractUpdate
* @throws \ReflectionException
* @throws SecurityException
* @throws SerializationException
* @throws \LogicException
*/
public function getUpdate(?ServerRequestInterface $request = null): AbstractUpdate
{
if ($request === null) {
if (!class_exists(\GuzzleHttp\Psr7\ServerRequest::class)) {
@@ -235,51 +53,28 @@ final class WebhookHandler
$request = \GuzzleHttp\Psr7\ServerRequest::fromGlobals();
}
return $this->parseUpdate($request);
}
/**
* Parses the raw request data and returns a typed Update object.
*
* @param ServerRequestInterface $request
*
* @return AbstractUpdate
* @throws \ReflectionException
* @throws SecurityException
* @throws SerializationException
* @throws \LogicException
*/
public function parseUpdate(ServerRequestInterface $request): AbstractUpdate
{
$payload = (string)$request->getBody();
$signature = $request->getHeaderLine('X-Max-Bot-Api-Secret');
$this->logger->debug('Received webhook payload', ['body' => $payload]);
if (empty($payload)) {
throw new SerializationException('Webhook body is empty.');
}
$this->verifySignature($signature);
$this->verifySignature($request->getHeaderLine('X-Max-Bot-Api-Secret'));
try {
$data = json_decode($payload, true, 512, JSON_THROW_ON_ERROR);
} catch (\JsonException $e) {
$this->logger->error('Failed to decode webhook JSON', ['payload' => $payload, 'exception' => $e]);
throw new SerializationException('Failed to decode webhook body as JSON.', 0, $e);
}
return $this->modelFactory->createUpdate($data);
}
$update = $this->modelFactory->createUpdate($data);
/**
* Dispatches a parsed Update object to its registered handler.
*
* @param AbstractUpdate $update
*/
public function dispatch(AbstractUpdate $update): void
{
$handler = $this->handlers[$update->updateType->value] ?? null;
$this->dispatcher->dispatch($update);
if ($handler) {
$handler($update, $this->api);
if (!headers_sent()) {
http_response_code(200);
}
}
@@ -297,6 +92,7 @@ final class WebhookHandler
}
if (!hash_equals($this->secret, $signature)) {
$this->logger->warning('Webhook signature verification failed', ['received_signature' => $signature]);
throw new SecurityException('Signature verification failed.');
}
}
+101
View File
@@ -0,0 +1,101 @@
<?php
declare(strict_types=1);
namespace BushlanovDev\MaxMessengerBot\Tests;
use BushlanovDev\MaxMessengerBot\Api;
use BushlanovDev\MaxMessengerBot\ClientApiInterface;
use BushlanovDev\MaxMessengerBot\LongPollingHandler;
use BushlanovDev\MaxMessengerBot\ModelFactory;
use BushlanovDev\MaxMessengerBot\UpdateDispatcher;
use BushlanovDev\MaxMessengerBot\WebhookHandler;
use PHPUnit\Framework\Attributes\CoversClass;
use PHPUnit\Framework\Attributes\Test;
use PHPUnit\Framework\Attributes\UsesClass;
use PHPUnit\Framework\MockObject\MockObject;
use PHPUnit\Framework\TestCase;
use Psr\Log\LoggerInterface;
use ReflectionClass;
#[CoversClass(Api::class)]
#[UsesClass(UpdateDispatcher::class)]
#[UsesClass(WebhookHandler::class)]
#[UsesClass(LongPollingHandler::class)]
final class ApiFactoryMethodsTest extends TestCase
{
private MockObject&ClientApiInterface $clientMock;
private MockObject&ModelFactory $modelFactoryMock;
private MockObject&LoggerInterface $loggerMock;
private Api $api;
protected function setUp(): void
{
$this->clientMock = $this->createMock(ClientApiInterface::class);
$this->modelFactoryMock = $this->createMock(ModelFactory::class);
$this->loggerMock = $this->createMock(LoggerInterface::class);
$this->api = new Api(
'fake-token',
$this->clientMock,
$this->modelFactoryMock,
$this->loggerMock,
);
}
#[Test]
public function createWebhookHandlerReturnsCorrectlyConfiguredInstance(): void
{
$secret = 'my-test-secret';
$webhookHandler = $this->api->createWebhookHandler($secret);
$this->assertInstanceOf(WebhookHandler::class, $webhookHandler);
$this->assertSame(
$this->getPrivateProperty($this->api, 'updateDispatcher'),
$this->getPrivateProperty($webhookHandler, 'dispatcher'),
);
$this->assertSame(
$this->getPrivateProperty($this->api, 'modelFactory'),
$this->getPrivateProperty($webhookHandler, 'modelFactory'),
);
$this->assertSame(
$this->getPrivateProperty($this->api, 'logger'),
$this->getPrivateProperty($webhookHandler, 'logger'),
);
$this->assertSame(
$secret,
$this->getPrivateProperty($webhookHandler, 'secret'),
);
}
#[Test]
public function createLongPollingHandlerReturnsCorrectlyConfiguredInstance(): void
{
$longPollingHandler = $this->api->createLongPollingHandler();
$this->assertInstanceOf(LongPollingHandler::class, $longPollingHandler);
$this->assertSame(
$this->api,
$this->getPrivateProperty($longPollingHandler, 'api')
);
$this->assertSame(
$this->getPrivateProperty($this->api, 'updateDispatcher'),
$this->getPrivateProperty($longPollingHandler, 'dispatcher')
);
$this->assertSame(
$this->getPrivateProperty($this->api, 'logger'),
$this->getPrivateProperty($longPollingHandler, 'logger')
);
}
private function getPrivateProperty(object $object, string $propertyName): mixed
{
$reflection = new ReflectionClass($object);
$property = $reflection->getProperty($propertyName);
return $property->getValue($object);
}
}
+1133 -353
View File
File diff suppressed because it is too large Load Diff
+171 -11
View File
@@ -28,6 +28,7 @@ use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\StreamFactoryInterface;
use Psr\Http\Message\StreamInterface;
use Psr\Log\LoggerInterface;
#[CoversClass(Client::class)]
final class ClientTest extends TestCase
@@ -42,6 +43,7 @@ final class ClientTest extends TestCase
private MockObject&RequestInterface $requestMock;
private MockObject&ResponseInterface $responseMock;
private MockObject&StreamInterface $streamMock;
private MockObject&LoggerInterface $loggerMock;
private Client $client;
@@ -61,6 +63,7 @@ final class ClientTest extends TestCase
$this->requestMock = $this->createMock(RequestInterface::class);
$this->responseMock = $this->createMock(ResponseInterface::class);
$this->streamMock = $this->createMock(StreamInterface::class);
$this->loggerMock = $this->createMock(LoggerInterface::class);
// Common mock setups
$this->requestFactoryMock->method('createRequest')->willReturn($this->requestMock);
@@ -75,6 +78,7 @@ final class ClientTest extends TestCase
$this->streamFactory,
self::API_BASE_URL,
self::API_VERSION,
$this->loggerMock,
);
}
@@ -309,8 +313,8 @@ final class ClientTest extends TestCase
$this->responseMock->method('getStatusCode')->willReturn(200);
$this->streamMock->method('__toString')->willReturn(json_encode($responsePayload));
$result = $this->client->upload($uploadUrl, $fileContents, $fileName);
$this->assertSame($responsePayload, $result);
$result = $this->client->multipartUpload($uploadUrl, $fileContents, $fileName);
$this->assertSame(json_encode($responsePayload), $result);
}
#[Test]
@@ -328,13 +332,13 @@ final class ClientTest extends TestCase
$this->requestFactoryMock->method('createRequest')->willReturn($this->requestMock);
$this->requestMock->method('withHeader')->willReturn($this->requestMock);
$this->requestMock->method('withBody')->willReturn($this->requestMock);
$this->httpClientMock->method('sendRequest')->willReturn($this->responseMock);
// $this->httpClientMock->method('sendRequest')->willReturn($this->responseMock);
$this->responseMock->method('getStatusCode')->willReturn(200);
$this->streamMock->method('__toString')->willReturn(json_encode($responsePayload));
$result = $this->client->upload($uploadUrl, $tmpFileHandle, $fileName);
$result = $this->client->multipartUpload($uploadUrl, $tmpFileHandle, $fileName);
$this->assertSame($responsePayload, $result);
$this->assertSame(json_encode($responsePayload), $result);
fclose($tmpFileHandle);
}
@@ -354,26 +358,182 @@ final class ClientTest extends TestCase
->with($this->requestMock)
->willThrowException($psrException);
$this->client->upload('http://some.url', 'content', 'file.txt');
$this->client->multipartUpload('http://some.url', 'content', 'file.txt');
}
#[Test]
public function uploadThrowsSerializationExceptionOnInvalidJsonResponse(): void
public function requestLogsRequestAndResponseOnDebugLevel(): void
{
$this->expectException(SerializationException::class);
$this->expectExceptionMessage('Failed to decode upload server response JSON.');
$this->responseMock->method('getStatusCode')->willReturn(200);
$this->streamMock->method('__toString')->willReturn('{"success":true}');
$this->loggerMock
->expects($this->exactly(2))
->method('debug');
$this->client->request('GET', '/me');
}
#[Test]
public function handleErrorResponseLogsWarning(): void
{
$this->responseMock->method('getStatusCode')->willReturn(404);
$this->streamMock->method('__toString')->willReturn('{"code":"not.found","message":"Not Found"}');
$this->loggerMock
->expects($this->once())
->method('error')
->with('API error response received', $this->anything());
$this->expectException(NotFoundException::class);
$this->client->request('GET', '/not/found');
}
#[Test]
public function uploadMethodReturnsRawStringResponse(): void
{
$uploadUrl = 'https://upload.server/path';
$fileContents = 'data';
$fileName = 'file.txt';
$rawResponse = '<retval>1</retval>';
$this->requestFactoryMock->method('createRequest')->willReturn($this->requestMock);
$this->requestMock->method('withHeader')->willReturn($this->requestMock);
$this->requestMock->method('withBody')->willReturn($this->requestMock);
$this->httpClientMock->method('sendRequest')->willReturn($this->responseMock);
$this->responseMock->method('getStatusCode')->willReturn(200);
$this->streamMock->method('__toString')->willReturn($rawResponse);
$result = $this->client->multipartUpload($uploadUrl, $fileContents, $fileName);
$this->assertSame($rawResponse, $result);
}
#[Test]
public function resumableUploadThrowsExceptionForInvalidResource(): void
{
$this->expectException(InvalidArgumentException::class);
$this->expectExceptionMessage('fileResource must be a valid stream resource.');
$this->client->resumableUpload('http://a.b', 'not-a-resource', 'file.txt', 100);
}
#[Test]
public function resumableUploadThrowsExceptionForZeroFileSize(): void
{
$this->expectException(InvalidArgumentException::class);
$this->expectExceptionMessage('File size must be greater than 0.');
$fileResource = fopen('php://memory', 'r');
$this->client->resumableUpload('http://a.b', $fileResource, 'file.txt', 0);
fclose($fileResource);
}
#[Test]
public function resumableUploadThrowsNetworkExceptionOnChunkUploadFailure(): void
{
$this->expectException(NetworkException::class);
$fileResource = fopen('php://memory', 'w+');
fwrite($fileResource, 'some data');
rewind($fileResource);
$this->requestFactoryMock->method('createRequest')->willReturn($this->requestMock);
$this->requestMock->method('withBody')->willReturnSelf();
$this->requestMock->method('withHeader')->willReturnSelf();
$psrException = new class extends \Exception implements ClientExceptionInterface {};
$this->httpClientMock
->method('sendRequest')
->willThrowException($psrException);
$this->client->resumableUpload('http://a.b', $fileResource, 'file.txt', 9);
fclose($fileResource);
}
#[Test]
public function resumableUploadSuccessfullyUploadsSingleChunk(): void
{
$fileContents = 'test-data';
$fileResource = fopen('php://memory', 'w+');
fwrite($fileResource, $fileContents);
rewind($fileResource);
$uploadUrl = 'http://a.b';
$fileName = 'file.txt';
$fileSize = strlen($fileContents);
$this->requestFactoryMock->method('createRequest')->willReturn($this->requestMock);
$this->requestMock->method('withBody')->willReturnSelf();
$this->requestMock->method('withHeader')->willReturnSelf();
$this->httpClientMock
->expects($this->once())
->method('sendRequest')
->with($this->requestMock)
->willReturn($this->responseMock);
$this->responseMock->method('getStatusCode')->willReturn(200);
$this->streamMock->method('__toString')->willReturn('{not-a-valid-json');
$this->client->upload('http://some.url', 'content', 'file.txt');
$this->streamMock->method('__toString')->willReturn('<retval>1</retval>');
$result = $this->client->resumableUpload($uploadUrl, $fileResource, $fileName, $fileSize);
$this->assertSame('<retval>1</retval>', $result);
fclose($fileResource);
}
#[Test]
public function resumableUploadSuccessfullyUploadsMultipleChunks(): void
{
$fileContents = str_repeat('A', 3 * 1024 * 1024); // 3 MB
$fileResource = fopen('php://memory', 'w+');
fwrite($fileResource, $fileContents);
rewind($fileResource);
$uploadUrl = 'http://a.b';
$fileName = 'bigfile.bin';
$fileSize = strlen($fileContents);
$this->requestFactoryMock->method('createRequest')->willReturn($this->requestMock);
$this->requestMock->method('withBody')->willReturnSelf();
$this->requestMock->method('withHeader')->willReturnSelf();
$this->httpClientMock
->expects($this->exactly(3))
->method('sendRequest')
->willReturnOnConsecutiveCalls(
$this->responseMock,
$this->responseMock,
$this->responseMock,
);
$this->responseMock->method('getStatusCode')->willReturn(200);
$this->streamMock
->method('__toString')
->willReturnOnConsecutiveCalls('', '', '<retval>1</retval>');
$result = $this->client->resumableUpload($uploadUrl, $fileResource, $fileName, $fileSize, 1024 * 1024);
$this->assertSame('<retval>1</retval>', $result);
fclose($fileResource);
}
#[Test]
public function resumableUploadStopsOnEmptyChunk(): void
{
$fileResource = fopen('php://memory', 'w+');
rewind($fileResource);
$uploadUrl = 'http://a.b';
$fileName = 'empty.txt';
$this->requestFactoryMock->expects($this->never())->method('createRequest');
$this->httpClientMock->expects($this->never())->method('sendRequest');
$result = $this->client->resumableUpload($uploadUrl, $fileResource, $fileName, 100);
$this->assertSame('', $result);
fclose($fileResource);
}
}
@@ -0,0 +1,103 @@
<?php
declare(strict_types=1);
namespace BushlanovDev\MaxMessengerBot\Tests\Laravel\Commands;
use BushlanovDev\MaxMessengerBot\Laravel\Commands\PollingStartCommand;
use BushlanovDev\MaxMessengerBot\Laravel\MaxBotManager;
use Illuminate\Support\Facades\Log;
use PHPUnit\Framework\Attributes\CoversClass;
use PHPUnit\Framework\Attributes\Test;
use PHPUnit\Framework\Attributes\UsesClass;
use PHPUnit\Framework\MockObject\MockObject;
use Symfony\Component\Console\Application as ConsoleApplication;
use Symfony\Component\Console\Tester\CommandTester;
#[CoversClass(PollingStartCommand::class)]
#[UsesClass(MaxBotManager::class)]
final class PollingStartCommandTest extends TestCase
{
private MockObject&MaxBotManager $botManagerMock;
private PollingStartCommand $command;
protected function setUp(): void
{
parent::setUp();
$this->botManagerMock = $this->createMock(MaxBotManager::class);
$this->container->instance(MaxBotManager::class, $this->botManagerMock);
$this->container->alias(MaxBotManager::class, 'maxbot.manager');
$this->command = new PollingStartCommand();
$this->command->setLaravel($this->container);
$application = new ConsoleApplication();
$application->add($this->command);
$commandInApp = $application->find('maxbot:polling:start');
$this->tester = new CommandTester($commandInApp);
}
#[Test]
public function handleSuccessfullyCallsManagerWithCustomTimeout(): void
{
$timeout = 60;
$this->botManagerMock
->expects($this->once())
->method('startLongPolling')
->with($timeout);
$this->tester->execute(['--timeout' => $timeout]);
$this->tester->assertCommandIsSuccessful();
$output = $this->tester->getDisplay();
$this->assertStringContainsString("Starting long polling with a timeout of $timeout seconds...", $output);
}
#[Test]
public function handleSuccessfullyUsesDefaultTimeout(): void
{
$defaultTimeout = 90;
$this->botManagerMock
->expects($this->once())
->method('startLongPolling')
->with($defaultTimeout);
$this->tester->execute([]);
$this->tester->assertCommandIsSuccessful();
$output = $this->tester->getDisplay();
$this->assertStringContainsString(
"Starting long polling with a timeout of $defaultTimeout seconds...",
$output
);
}
#[Test]
public function handleCatchesExceptionAndLogsError(): void
{
$exceptionMessage = 'Something went wrong';
$exception = new \RuntimeException($exceptionMessage);
$this->botManagerMock
->expects($this->once())
->method('startLongPolling')
->willThrowException($exception);
Log::shouldReceive('error')
->once()
->with(
"Long polling failed to start or crashed: $exceptionMessage",
['exception' => $exception],
);
$statusCode = $this->tester->execute([]);
$this->assertSame(1, $statusCode, 'Command should return a failure exit code.');
$output = $this->tester->getDisplay();
$this->assertStringContainsString("❌ Long polling failed: $exceptionMessage", $output);
}
}
+48
View File
@@ -0,0 +1,48 @@
<?php
declare(strict_types=1);
namespace BushlanovDev\MaxMessengerBot\Tests\Laravel\Commands;
use Illuminate\Container\Container;
use Illuminate\Support\Facades\Facade;
use PHPUnit\Framework\TestCase as TestCaseOriginal;
use Psr\Log\LoggerInterface;
use Symfony\Component\Console\Tester\CommandTester;
abstract class TestCase extends TestCaseOriginal
{
protected Container $container;
protected CommandTester $tester;
protected function setUp(): void
{
parent::setUp();
$this->container = new TestApplicationContainer();
Container::setInstance($this->container);
Facade::setFacadeApplication($this->container);
$loggerMock = $this->createMock(LoggerInterface::class);
$this->container->instance('log', $loggerMock);
}
protected function tearDown(): void
{
Container::setInstance(null);
Facade::clearResolvedInstances();
if (class_exists(\Mockery::class)) {
\Mockery::close();
}
parent::tearDown();
}
}
class TestApplicationContainer extends Container
{
public function runningUnitTests(): bool
{
return true;
}
}
@@ -0,0 +1,118 @@
<?php
declare(strict_types=1);
namespace BushlanovDev\MaxMessengerBot\Tests\Laravel\Commands;
use BushlanovDev\MaxMessengerBot\Api;
use BushlanovDev\MaxMessengerBot\Enums\UpdateType;
use BushlanovDev\MaxMessengerBot\Laravel\Commands\WebhookListCommand;
use BushlanovDev\MaxMessengerBot\Models\Subscription;
use Illuminate\Support\Facades\Log;
use PHPUnit\Framework\Attributes\CoversClass;
use PHPUnit\Framework\Attributes\Test;
use PHPUnit\Framework\Attributes\UsesClass;
use PHPUnit\Framework\MockObject\MockObject;
use Symfony\Component\Console\Application as ConsoleApplication;
use Symfony\Component\Console\Tester\CommandTester;
#[CoversClass(WebhookListCommand::class)]
#[UsesClass(Api::class)]
#[UsesClass(Subscription::class)]
final class WebhookListCommandTest extends TestCase
{
private MockObject&Api $apiMock;
private WebhookListCommand $command;
protected function setUp(): void
{
parent::setUp();
$this->apiMock = $this->createMock(Api::class);
$this->container->instance(Api::class, $this->apiMock);
$this->command = new WebhookListCommand();
$this->command->setLaravel($this->container);
$application = new ConsoleApplication();
$application->add($this->command);
$commandInApp = $application->find('maxbot:webhook:list');
$this->tester = new CommandTester($commandInApp);
}
#[Test]
public function handleDisplaysTableWithActiveSubscriptions(): void
{
$timestamp = 1678886400; // 2023-03-15 13:20:00 UTC
$subscriptions = [
new Subscription(
'https://example.com/hook1',
$timestamp,
[UpdateType::MessageCreated, UpdateType::BotStarted],
'0.0.6'
),
new Subscription(
'https://example.com/hook2',
$timestamp + 3600,
null, // Should be rendered as 'all'
'0.0.6'
),
];
$this->apiMock
->expects($this->once())
->method('getSubscriptions')
->willReturn($subscriptions);
$this->tester->execute([]);
$this->tester->assertCommandIsSuccessful();
$output = $this->tester->getDisplay();
$this->assertStringContainsString('https://example.com/hook1', $output);
$this->assertStringContainsString('https://example.com/hook2', $output);
$this->assertStringContainsString('message_created, bot_started', $output);
$this->assertStringContainsString('all', $output);
$this->assertStringContainsString(date('Y-m-d H:i:s', $timestamp), $output);
$this->assertStringContainsString(date('Y-m-d H:i:s', $timestamp + 3600), $output);
}
#[Test]
public function handleDisplaysMessageWhenNoSubscriptionsExist(): void
{
$this->apiMock
->expects($this->once())
->method('getSubscriptions')
->willReturn([]);
$this->tester->execute([]);
$this->tester->assertCommandIsSuccessful();
$output = $this->tester->getDisplay();
$this->assertStringContainsString('No active webhook subscriptions found.', $output);
$this->assertStringNotContainsString('URL', $output, 'Table headers should not be displayed.');
}
#[Test]
public function handleCatchesExceptionAndLogsError(): void
{
$exceptionMessage = 'API is down';
$exception = new \RuntimeException($exceptionMessage);
$this->apiMock
->expects($this->once())
->method('getSubscriptions')
->willThrowException($exception);
Log::shouldReceive('error')
->once()
->with("Webhook list error: $exceptionMessage", ['exception' => $exception]);
$statusCode = $this->tester->execute([]);
$this->assertSame(1, $statusCode, 'Command should return a failure exit code.');
$output = $this->tester->getDisplay();
$this->assertStringContainsString("❌ Webhook list error: $exceptionMessage", $output);
}
}
@@ -0,0 +1,163 @@
<?php
declare(strict_types=1);
namespace BushlanovDev\MaxMessengerBot\Tests\Laravel\Commands;
use BushlanovDev\MaxMessengerBot\Api;
use BushlanovDev\MaxMessengerBot\Enums\UpdateType;
use BushlanovDev\MaxMessengerBot\Laravel\Commands\WebhookSubscribeCommand;
use BushlanovDev\MaxMessengerBot\Models\Result;
use Illuminate\Contracts\Config\Repository as Config;
use Illuminate\Support\Facades\Log;
use PHPUnit\Framework\Attributes\CoversClass;
use PHPUnit\Framework\Attributes\Test;
use PHPUnit\Framework\Attributes\UsesClass;
use PHPUnit\Framework\MockObject\MockObject;
use Symfony\Component\Console\Application as ConsoleApplication;
use Symfony\Component\Console\Tester\CommandTester;
#[CoversClass(WebhookSubscribeCommand::class)]
#[UsesClass(Api::class)]
#[UsesClass(Result::class)]
final class WebhookSubscribeCommandTest extends TestCase
{
private MockObject&Api $apiMock;
private MockObject&Config $configMock;
private WebhookSubscribeCommand $command;
protected function setUp(): void
{
parent::setUp();
$this->apiMock = $this->createMock(Api::class);
$this->configMock = $this->createMock(Config::class);
$this->container->instance(Api::class, $this->apiMock);
$this->container->instance(Config::class, $this->configMock);
$this->command = new WebhookSubscribeCommand();
$this->command->setLaravel($this->container);
$application = new ConsoleApplication();
$application->add($this->command);
$commandInApp = $application->find('maxbot:webhook:subscribe');
$this->tester = new CommandTester($commandInApp);
}
#[Test]
public function handleSuccessfullySubscribesWithAllOptions(): void
{
$url = 'https://example.com/webhook';
$secret = 'my-super-secret';
$types = ['message_created', 'bot_started'];
$expectedUpdateTypes = [UpdateType::MessageCreated, UpdateType::BotStarted];
$this->apiMock
->expects($this->once())
->method('subscribe')
->with($url, $secret, $expectedUpdateTypes)
->willReturn(new Result(true, null));
$this->tester->execute([
'url' => $url,
'--secret' => $secret,
'--types' => $types,
]);
$this->tester->assertCommandIsSuccessful();
$output = $this->tester->getDisplay();
$this->assertStringContainsString('✅ Successfully subscribed to webhook!', $output);
$this->assertStringContainsString("URL: $url", $output);
$this->assertStringContainsString("Secret: ***************", $output);
$this->assertStringContainsString("Update types: message_created, bot_started", $output);
}
#[Test]
public function handleUsesSecretFromConfigWhenOptionIsNotProvided(): void
{
$url = 'https://example.com/webhook';
$configSecret = 'secret-from-config';
$this->configMock
->expects($this->once())
->method('get')
->with('maxbot.webhook_secret')
->willReturn($configSecret);
$this->apiMock
->expects($this->once())
->method('subscribe')
->with($url, $configSecret, null)
->willReturn(new Result(true, null));
$this->tester->execute(['url' => $url]);
$this->tester->assertCommandIsSuccessful();
}
#[Test]
public function handleFailsForInvalidUrl(): void
{
$this->apiMock->expects($this->never())->method('subscribe');
$statusCode = $this->tester->execute(['url' => 'not-a-valid-url']);
$this->assertSame(1, $statusCode);
$this->assertStringContainsString('Invalid URL provided.', $this->tester->getDisplay());
}
#[Test]
public function handleFailsForInvalidUpdateType(): void
{
$this->apiMock->expects($this->never())->method('subscribe');
$statusCode = $this->tester->execute([
'url' => 'https://example.com',
'--types' => ['message_created', 'invalid_type'],
]);
$this->assertSame(1, $statusCode);
$this->assertStringContainsString('Invalid update type: invalid_type', $this->tester->getDisplay());
}
#[Test]
public function handleDisplaysApiErrorMessageOnFailure(): void
{
$url = 'https://example.com/webhook';
$apiErrorMessage = 'URL is already subscribed';
$this->apiMock
->expects($this->once())
->method('subscribe')
->willReturn(new Result(false, $apiErrorMessage));
$statusCode = $this->tester->execute(['url' => $url]);
$this->assertSame(1, $statusCode);
$output = $this->tester->getDisplay();
$this->assertStringContainsString('❌ Failed to subscribe to webhook.', $output);
$this->assertStringContainsString("Response: $apiErrorMessage", $output);
}
#[Test]
public function handleCatchesExceptionAndLogsError(): void
{
$url = 'https://example.com/webhook';
$exceptionMessage = 'Network error';
$exception = new \RuntimeException($exceptionMessage);
$this->apiMock
->expects($this->once())
->method('subscribe')
->willThrowException($exception);
Log::shouldReceive('error')
->once()
->with("Webhook subscription error: $exceptionMessage", ['exception' => $exception]);
$statusCode = $this->tester->execute(['url' => $url]);
$this->assertSame(1, $statusCode);
$output = $this->tester->getDisplay();
$this->assertStringContainsString("❌ Webhook subscription error: $exceptionMessage", $output);
}
}
@@ -0,0 +1,130 @@
<?php
declare(strict_types=1);
namespace BushlanovDev\MaxMessengerBot\Tests\Laravel\Commands;
use BushlanovDev\MaxMessengerBot\Api;
use BushlanovDev\MaxMessengerBot\Laravel\Commands\WebhookUnsubscribeCommand;
use BushlanovDev\MaxMessengerBot\Models\Result;
use Illuminate\Support\Facades\Log;
use PHPUnit\Framework\Attributes\CoversClass;
use PHPUnit\Framework\Attributes\Test;
use PHPUnit\Framework\Attributes\UsesClass;
use PHPUnit\Framework\MockObject\MockObject;
use Symfony\Component\Console\Application as ConsoleApplication;
use Symfony\Component\Console\Tester\CommandTester;
#[CoversClass(WebhookUnsubscribeCommand::class)]
#[UsesClass(Api::class)]
#[UsesClass(Result::class)]
final class WebhookUnsubscribeCommandTest extends TestCase
{
private MockObject&Api $apiMock;
private WebhookUnsubscribeCommand $command;
protected function setUp(): void
{
parent::setUp();
$this->apiMock = $this->createMock(Api::class);
$this->container->instance(Api::class, $this->apiMock);
$this->command = new WebhookUnsubscribeCommand();
$this->command->setLaravel($this->container);
$application = new ConsoleApplication();
$application->add($this->command);
$commandInApp = $application->find('maxbot:webhook:unsubscribe');
$this->tester = new CommandTester($commandInApp);
}
#[Test]
public function handleSuccessfullyUnsubscribesWithConfirmationFlag(): void
{
$url = 'https://example.com/webhook';
$this->apiMock
->expects($this->once())
->method('unsubscribe')
->with($url)
->willReturn(new Result(true, null));
$this->tester->execute([
'url' => $url,
'--confirm' => true,
]);
$this->tester->assertCommandIsSuccessful();
$output = $this->tester->getDisplay();
$this->assertStringContainsString('✅ Successfully unsubscribed from webhook!', $output);
}
#[Test]
public function handleCancelsWhenNotConfirmed(): void
{
$url = 'https://example.com/webhook';
$this->apiMock->expects($this->never())->method('unsubscribe');
$this->tester->setInputs(['no']);
$this->tester->execute(['url' => $url]);
$this->tester->assertCommandIsSuccessful();
$output = $this->tester->getDisplay();
$this->assertStringContainsString('Are you sure you want to unsubscribe', $output);
$this->assertStringContainsString('Operation cancelled.', $output);
}
#[Test]
public function handleFailsForInvalidUrl(): void
{
$this->apiMock->expects($this->never())->method('unsubscribe');
$statusCode = $this->tester->execute(['url' => 'not-a-valid-url']);
$this->assertSame(1, $statusCode);
$this->assertStringContainsString('Invalid URL provided.', $this->tester->getDisplay());
}
#[Test]
public function handleDisplaysApiErrorMessageOnFailure(): void
{
$url = 'https://example.com/webhook';
$apiErrorMessage = 'Subscription not found';
$this->apiMock
->expects($this->once())
->method('unsubscribe')
->willReturn(new Result(false, $apiErrorMessage));
$statusCode = $this->tester->execute(['url' => $url, '--confirm' => true]);
$this->assertSame(1, $statusCode);
$output = $this->tester->getDisplay();
$this->assertStringContainsString('❌ Failed to unsubscribe from webhook.', $output);
$this->assertStringContainsString("Response: $apiErrorMessage", $output);
}
#[Test]
public function handleCatchesExceptionAndLogsError(): void
{
$url = 'https://example.com/webhook';
$exceptionMessage = 'API connection refused';
$exception = new \RuntimeException($exceptionMessage);
$this->apiMock
->expects($this->once())
->method('unsubscribe')
->willThrowException($exception);
Log::shouldReceive('error')
->once()
->with("Webhook unsubscribe error: $exceptionMessage", ['exception' => $exception]);
$statusCode = $this->tester->execute(['url' => $url, '--confirm' => true]);
$this->assertSame(1, $statusCode);
$output = $this->tester->getDisplay();
$this->assertStringContainsString("❌ Webhook unsubscribe error: $exceptionMessage", $output);
}
}

Some files were not shown because too many files have changed in this diff Show More