Compare commits

...

78 Commits

Author SHA1 Message Date
Alex efd6261490 Added chat admin permissions 2026-04-15 22:10:15 +03:00
Alex dd295efc3d tag 1.6.0 2026-03-22 09:23:35 +03:00
Alex 85231b0962 Removed deprecated DataAttachment 2026-03-21 09:44:40 +03:00
Alex 40742ddc60 Removed deprecated ReplyKeyboardAttachment #27 2026-03-20 22:55:36 +03:00
Alex 1e48123ee3 Updated webhook documentation #26 2026-03-13 20:54:49 +03:00
Alex affe904bed tag 1.5.1 2026-03-07 09:47:01 +03:00
Alex 6c4e0c8ca7 Merge pull request #24 from imperiumbee/master
Added payload param to openAppButton
2026-03-07 09:25:53 +03:00
imperiumbee 3eb3e07bfa Added payload param to openAppButton 2026-03-06 11:12:20 +03:00
Alex ab7ea25796 Месседжер MAX следит за пользователями VPN 2026-03-05 15:24:24 +03:00
Alex 2a97a15889 1.5.0 2025-12-20 20:36:59 +03:00
Alex e9904cec71 Merge pull request #23 from BushlanovDev/1.5.0
1.5.0
2025-12-20 20:35:00 +03:00
Alex 67463a6b64 Replacing the User object with UserWithPhoto #22 2025-12-19 13:30:36 +03:00
Alex 3c6da8e8f6 Added MessageButton & ChatAdminPermission::EditLink & alias in ChatAdmin & participants in Chat & first_name in BotPatch 2025-12-18 19:50:58 +03:00
Alex cbb4cbcf0e Removed the typo 2025-12-10 21:51:13 +03:00
Alex a7773c0b93 Added AttachmentNotReadyException (#19) 2025-12-06 15:15:39 +03:00
Alex 79d406da27 ShareAttachmentRequestPayload & PhotoAttachmentRequestPayload update exception rule (#18) 2025-12-05 13:53:07 +03:00
Alex ef3b76394c tag 1.4.0 2025-12-04 08:44:10 +03:00
Alex 2ecb5c7b04 Merge pull request #17 from BushlanovDev/i15
Silent mode for errors of unsupported event types #15
2025-12-04 08:41:54 +03:00
Alex 2e7e9d987f Added DialogUnmuted & DialogCleared & DialogRemoved update types 2025-12-03 23:05:09 +03:00
Alex cf415b70e9 Added DialogMuted & BotStopped update types 2025-12-02 20:00:34 +03:00
Alex a94dfe0df4 Silent mode for errors of unsupported event types #15 2025-12-01 20:11:47 +03:00
Alex 03b1f158d9 Disabled api version #16 2025-11-30 17:10:00 +03:00
Alex d853faacf7 tag 1.3.2 2025-10-21 09:05:51 +03:00
Alex 576f02efbd Merge pull request #14 from BushlanovDev/i12
fix 12
2025-10-21 09:02:44 +03:00
Alex da7a07145b Fix send message response object 2025-10-20 21:27:54 +03:00
Alex 7cdbfc0f47 Update Message model 2025-10-08 23:14:06 +03:00
Alex f29344d2ec Update Message model 2025-10-07 23:56:57 +03:00
Alex 3012272497 Merge pull request #11 from BushlanovDev/fix10
Fix authorization with header #10
2025-10-04 21:54:19 +03:00
Alex 0dc10bd279 Fix authorization with header #10 2025-10-04 21:51:14 +03:00
Alex 8419a7892d Merge remote-tracking branch 'origin/master' 2025-09-29 19:28:41 +03:00
Alex ddc57d7ab8 Change api domain and authorization with header 2025-09-29 19:28:20 +03:00
Alex d0f044c7bd Change api domain and authorization with header 2025-09-29 19:25:28 +03:00
Alex 31f109db7e Merge pull request #8 from BushlanovDev/docs
Update documentation
2025-09-16 21:25:38 +03:00
Alex e1375acabb Update documentation 2025-09-16 21:22:04 +03:00
Alex 098aa44825 Update documentation 2025-09-15 23:04:15 +03:00
Alex 6137b2ea6e Merge pull request #7 from BushlanovDev/docs
Update documentation
2025-09-14 15:55:33 +03:00
Alex 122afcc7c0 Merge branch 'master' into docs 2025-09-14 15:44:19 +03:00
Alex 4d56119fa2 Disable deprecation error for unit test 2025-09-13 19:53:43 +03:00
Alex ae53f51854 Disable deprecation error for unit test 2025-09-13 19:26:13 +03:00
Alex b87b41ff8f Update documentation 2025-09-12 22:06:23 +03:00
Alex 493be1a9a0 Add php8.5 to github action 2025-09-10 21:25:52 +03:00
Alex 033fa42b79 Update library version 2025-09-02 21:32:26 +03:00
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
186 changed files with 17523 additions and 1585 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

+1 -12
View File
@@ -30,7 +30,7 @@ jobs:
runs-on: ubuntu-latest
strategy:
matrix:
php-versions: [ "8.3", "8.4" ]
php-versions: [ "8.3", "8.4", "8.5" ]
name: PHP ${{ matrix.php-versions }} Test on ubuntu-latest
steps:
@@ -43,17 +43,6 @@ jobs:
php-version: ${{ matrix.php-versions }}
coverage: xdebug
- name: Get composer cache directory
id: composer-cache
run: echo "dir=$(composer config cache-files-dir)" >> $GITHUB_OUTPUT
- name: Cache composer dependencies
uses: actions/cache@v3
with:
path: ${{ steps.composer-cache.outputs.dir }}
key: ${{ runner.os }}-composer-${{ hashFiles('**/composer.json') }}
restore-keys: ${{ runner.os }}-composer-
- name: Install composer dependencies
run: composer install --prefer-dist --no-interaction
+142 -38
View File
@@ -1,73 +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]
> Библиотека в стадии активной разработки.
> не рекомендую использовать его на реальных устройствах, с настоящим номером телефона, и для личной переписки.
> Обязательно к прочтению - [Месседжер MAX следит за пользователями VPN](https://habr.com/ru/articles/1006666/)
## Быстрый старт
> Если вы новичок, то можете прочитать [официальную документацию](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', // HTTPS 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`) *Отправка действия в чат (например, "печатает...").*
- [x] `GET /chats/{chatId}/pin` (`getPinnedMessage`) *Получение закрепленного сообщения.*
- [x] `PUT /chats/{chatId}/pin` (`pinMessage`) *Закрепление сообщения.*
- [x] `DELETE /chats/{chatId}/pin` (`unpinMessage`) *Открепление сообщения.*
- [x] `GET /chats/{chatId}/members/me` (`getMembership`) *Получение информации о членстве бота в чате.*
- [x] `DELETE /chats/{chatId}/members/me` (`leaveChat`) *Выход бота из чата.*
- [x] `GET /chats/{chatId}/members/admins` (`getAdmins`) *Получение администраторов чата.*
- [ ] `POST /chats/{chatId}/members/admins` (`postAdmins`) *Назначение администраторов чата.*
- [x] `DELETE /chats/{chatId}/members/admins/{userId}` (`deleteAdmins`) *Снятие прав администратора.*
- [x] `GET /chats/{chatId}/members` (`getMembers`) *Получение участников чата.*
- [ ] `POST /chats/{chatId}/members` (`addMembers`) *Добавление участников в чат.*
- [x] `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
- [x] `GET /messages` (`getMessages`) *Получение списка сообщений из чата.*
- [x] `POST /messages` (`sendMessage`) *Отправка сообщения.*
- [ ] `PUT /messages` (`editMessage`) *Редактирование сообщения.*
- [x] `DELETE /messages` (`deleteMessage`) *Удаление сообщения.*
- [x] `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-кнопки)
## Лицензия
+75 -50
View File
@@ -1,53 +1,78 @@
{
"name": "bushlanov-dev/max-bot-api-client-php",
"description": "Max Bot API Client library",
"keywords": ["max messenger", "bot", "max", "api"],
"type": "library",
"license": "MIT",
"authors": [
{
"name": "Aleksandr Bushlanov",
"email": "alex@bushlanov.dev",
"homepage": "https://bushlanov.dev",
"role": "Developer"
"name": "bushlanov-dev/max-bot-api-client-php",
"description": "Max Bot API Client library",
"keywords": [
"max messenger",
"bot",
"max",
"api",
"max bot",
"laravel",
"laravel max bot"
],
"type": "library",
"license": "MIT",
"authors": [
{
"name": "Aleksandr Bushlanov",
"email": "alex@bushlanov.dev",
"homepage": "https://bushlanov.dev",
"role": "Developer"
}
],
"require": {
"php": ">=8.3",
"ext-json": "*",
"guzzlehttp/guzzle": "^6.5.8||^7.0",
"guzzlehttp/psr7": "^1.8||^2.0",
"psr/http-client": "^1.0",
"psr/http-factory": "^1.0",
"psr/http-message": "^1.0||^2.0",
"psr/log": "^3.0"
},
"require-dev": {
"friendsofphp/php-cs-fixer": "^3.77",
"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",
"roave/security-advisories": "dev-latest"
},
"autoload": {
"psr-4": {
"BushlanovDev\\MaxMessengerBot\\": "src"
}
},
"autoload-dev": {
"psr-4": {
"BushlanovDev\\MaxMessengerBot\\Tests\\": "tests"
}
},
"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=512M",
"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 --square clover.xml .github/badge-coverage.svg"
]
}
],
"require": {
"php": ">=8.3",
"ext-json": "*",
"guzzlehttp/guzzle": "^6.5.8||^7.0",
"guzzlehttp/psr7": "^1.8||^2.0",
"psr/http-client": "^1.0",
"psr/http-factory": "^1.0",
"psr/http-message": "^1.0||^2.0"
},
"require-dev": {
"friendsofphp/php-cs-fixer": "^3.77",
"jaschilz/php-coverage-badger": "^2.0",
"mikey179/vfsstream": "^1.6",
"php-mock/php-mock-phpunit": "^2.13",
"phpstan/phpstan": "^2.1",
"phpunit/phpunit": "^12.0",
"roave/security-advisories": "dev-latest"
},
"autoload": {
"psr-4": {
"BushlanovDev\\MaxMessengerBot\\": "src"
}
},
"autoload-dev": {
"psr-4": {
"BushlanovDev\\MaxMessengerBot\\Tests\\": "tests"
}
},
"config": {
"sort-packages": true
},
"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"]
}
}
+616
View File
@@ -0,0 +1,616 @@
- [Быстрый старт](#Быстрый-старт)
- [Получение токена](#Получение-токена)
- [Установка библиотеки](#Установка-библиотеки)
- [Инициализация бота](#Инициализация-бота)
- [Информация о боте](#Информация-о-боте)
- `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-кнопки)
- [Laravel](#Laravel)
- [Регистрация пакета](#Регистрация-пакета)
- [Настройка](#Настройка)
- [Использование](#Использование)
- [Artisan команды](#Artisan-команды)
- [Подписка на Webhook](#Подписка-на-Webhook)
- [Удаление подписки](#Удаление-подписки)
- [Список подписок](#Список-подписок)
- [Обработка хуков](#Обработка-хуков)
- [Long Polling](#Long-Polling)
- [Handler Classes](#Handler-Classes)
- [Тестирование](#Тестирование)
## Быстрый старт
> Если вы новичок, то можете прочитать [официальную документацию](https://dev.max.ru/), написанную разработчиками Max.
### Получение токена
Откройте диалог с [MasterBot](https://max.ru/MasterBot), следуйте инструкциям и создайте нового бота. После создания
бота MasterBot отправит вам токен.
### Установка библиотеки
```bash
composer require bushlanov-dev/max-bot-api-client-php
```
### Инициализация бота
Единственной обязательной настройкой является токен вашего бота.
⚠️ Никогда, и ни при каких обстоятельствах не храните токен в коде. ⚠️
Используйте переменные окружения!
```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.
Судя по обновленной [документации](https://dev.max.ru/docs-api/methods/POST/subscriptions) поддерживается только 443 порт!
```php
$api->subscribe(
url: 'https://example.com/webhook', // HTTPS URL на который будут приходить хуки. Должен начинаться с https://
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, // Заполните это, если хотите просто отправить одноразовое уведомление пользователю (необязательно)
);
```
## 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, например:
```php
use MaxBot;
// Отправка сообщения пользователю
MaxBot::sendUserMessage(123456, 'Hello from Laravel!');
// Получение обновления
$updates = MaxBot::getUpdates();
```
### Artisan команды
#### Подписка на Webhook
```bash
# Подписка на получение обновлений
php artisan maxbot:webhook:subscribe https://yourapp.com/bot/webhook
# С верификацией
php artisan maxbot:webhook:subscribe https://yourapp.com/bot/webhook --secret=your_secret_key
# Подписка только на определенные типы событий
php artisan maxbot:webhook:subscribe https://yourapp.com/bot/webhook --types=message_created --types=message_callback
```
#### Удаление подписки
```bash
php artisan maxbot:webhook:unsubscribe https://yourapp.com/bot/webhook
```
#### Список подписок
```bash
php artisan maxbot:webhook:list
```
### Обработка хуков
Создайте контроллер для обработчика:
```php
use Illuminate\Http\Request;
use BushlanovDev\MaxMessengerBot\Laravel\MaxBotManager;
class WebhookController extends Controller
{
public function handle(Request $request, MaxBotManager $botManager)
{
// Обработчик сообщений
$botManager->onMessageCreated(function (MessageCreatedUpdate $update) {
$message = $update->message;
// ...
});
// Обработчик команды /start
$botManager->onCommand('start', function (MessageCreatedUpdate $update) {
// ...
});
// Using Laravel container bindings
$botManager->onMessageCreated(MessageHandler::class);
$botManager->onCommand('help', HelpCommandHandler::class);
return $botManager->handleWebhook($request);
}
}
```
Добавьте маршрут в `routes/web.php`:
```php
Route::post('/bot/webhook', [WebhookController::class, 'handle']);
```
### Long Polling
Создайте artisan команду для получения long polling обновлений:
```php
use Illuminate\Console\Command;
use BushlanovDev\MaxMessengerBot\Laravel\MaxBotManager;
class BotPollingCommand extends Command
{
protected $signature = 'bot:polling';
protected $description = 'Start bot long polling';
public function handle(MaxBotManager $botManager)
{
$this->info('Starting bot polling...');
$botManager->startLongPolling();
}
}
```
### Handler Classes
Примеры классов обработчиков обновлений:
```php
class MessageHandler
{
public function handle(MessageCreatedUpdate $update)
{
$message = $update->message;
$text = $message->body?->text;
if ($text) {
app(Api::class)->sendMessage(
userId: $message->sender->userId,
text: "You said: $text",
);
}
}
}
class HelpCommandHandler
{
public function handle(MessageCreatedUpdate $update)
{
app(Api::class)->sendMessage(
userId: $update->message->sender->userId,
text: "This is help message",
);
}
}
```
### Тестирование
Вы можете использовать мок API для тестирования:
```php
use BushlanovDev\MaxMessengerBot\Api;
class BotTest extends TestCase
{
public function test_bot_sends_message()
{
$apiMock = $this->createMock(Api::class);
$apiMock->expects($this->once())
->method('sendUserMessage')
->with(123456, 'Hello!');
$this->app->instance(Api::class, $apiMock);
// Your test code here
}
}
```
+3264
View File
File diff suppressed because it is too large Load Diff
+4659
View File
File diff suppressed because one or more lines are too long
+13 -3
View File
@@ -1,14 +1,20 @@
<?xml version="1.0" encoding="UTF-8"?>
<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="vendor/phpunit/phpunit/phpunit.xsd"
bootstrap="vendor/autoload.php"
bootstrap="tests/bootstrap.php"
testdox="false"
cacheDirectory=".phpunit.cache"
executionOrder="depends,defects"
requireCoverageMetadata="true"
beStrictAboutCoverageMetadata="true"
beStrictAboutOutputDuringTests="true"
displayDetailsOnPhpunitDeprecations="true"
failOnPhpunitDeprecation="true"
failOnDeprecation="false"
failOnPhpunitDeprecation="false"
displayDetailsOnPhpunitDeprecations="false"
displayDetailsOnTestsThatTriggerDeprecations="false"
displayDetailsOnTestsThatTriggerErrors="true"
displayDetailsOnTestsThatTriggerNotices="true"
displayDetailsOnTestsThatTriggerWarnings="true"
failOnRisky="true"
failOnWarning="true">
<testsuites>
@@ -25,4 +31,8 @@
<directory suffix=".php">src/Exceptions</directory>
</exclude>
</source>
<php>
<ini name="error_reporting" value="E_ALL &amp; ~E_DEPRECATED"/>
</php>
</phpunit>
+459 -148
View File
@@ -10,7 +10,6 @@ use BushlanovDev\MaxMessengerBot\Enums\UpdateType;
use BushlanovDev\MaxMessengerBot\Enums\UploadType;
use BushlanovDev\MaxMessengerBot\Exceptions\ClientApiException;
use BushlanovDev\MaxMessengerBot\Exceptions\NetworkException;
use BushlanovDev\MaxMessengerBot\Exceptions\SecurityException;
use BushlanovDev\MaxMessengerBot\Exceptions\SerializationException;
use BushlanovDev\MaxMessengerBot\Models\AbstractModel;
use BushlanovDev\MaxMessengerBot\Models\Attachments\Requests\AbstractAttachmentRequest;
@@ -19,20 +18,25 @@ use BushlanovDev\MaxMessengerBot\Models\Attachments\Requests\FileAttachmentReque
use BushlanovDev\MaxMessengerBot\Models\Attachments\Requests\PhotoAttachmentRequest;
use BushlanovDev\MaxMessengerBot\Models\Attachments\Requests\VideoAttachmentRequest;
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\Updates\AbstractUpdate;
use BushlanovDev\MaxMessengerBot\Models\UploadEndpoint;
use BushlanovDev\MaxMessengerBot\Models\VideoAttachmentDetails;
use InvalidArgumentException;
use JsonException;
use LogicException;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Log\LoggerInterface;
use Psr\Log\NullLogger;
use ReflectionException;
use RuntimeException;
@@ -44,13 +48,16 @@ use RuntimeException;
*/
class Api
{
private const string API_BASE_URL = 'https://botapi.max.ru';
public const string API_VERSION = '0.0.6';
public const string LIBRARY_VERSION = '1.6.1';
public const string API_VERSION = '1.2.5';
private const string API_BASE_URL = 'https://platform-api.max.ru';
private const string METHOD_GET = 'GET';
private const string METHOD_POST = 'POST';
private const string METHOD_DELETE = 'DELETE';
// private const string METHOD_PATCH = 'PATCH';
private const string METHOD_PATCH = 'PATCH';
private const string METHOD_PUT = 'PUT';
private const string ACTION_ME = '/me';
@@ -65,25 +72,41 @@ class Api
private const string ACTION_CHATS_MEMBERS_ADMINS_ID = '/chats/%d/members/admins/%d';
private const string ACTION_CHATS_MEMBERS = '/chats/%d/members';
private const string ACTION_UPDATES = '/updates';
private const string ACTION_ANSWERS = '/answers';
private const string ACTION_VIDEO_DETAILS = '/videos/%s';
private const int RESUMABLE_UPLOAD_THRESHOLD_BYTES = 10 * 1024 * 1024; // 10 MB
private readonly ClientApiInterface $client;
private readonly ModelFactory $modelFactory;
private readonly LoggerInterface $logger;
private readonly UpdateDispatcher $updateDispatcher;
/**
* Api constructor.
*
* @param string $accessToken Your bot's access token from @MasterBot.
* @param string|null $accessToken Your bot's access token from @MasterBot.
* @param ClientApiInterface|null $client Http api client.
* @param ModelFactory|null $modelFactory
* @param ModelFactory|null $modelFactory The model factory.
* @param LoggerInterface|null $logger PSR LoggerInterface.
*
* @throws InvalidArgumentException
*/
public function __construct(
string $accessToken,
?string $accessToken = null,
?ClientApiInterface $client = null,
?ModelFactory $modelFactory = null
?ModelFactory $modelFactory = null,
?LoggerInterface $logger = null,
) {
if (empty($accessToken) && $client === null) {
throw new InvalidArgumentException('You must provide either an access token or a client.');
}
$this->logger = $logger ?? new NullLogger();
if ($client === null) {
if (!class_exists(\GuzzleHttp\Client::class) || !class_exists(\GuzzleHttp\Psr7\HttpFactory::class)) {
throw new LogicException(
@@ -92,7 +115,12 @@ class Api
);
}
$guzzle = new \GuzzleHttp\Client();
$guzzle = new \GuzzleHttp\Client([
'timeout' => 10,
'connect_timeout' => 5,
'read_timeout' => 10,
'headers' => ['User-Agent' => 'max-bot-api-client-php/' . self::LIBRARY_VERSION . ' PHP/' . PHP_VERSION],
]);
$httpFactory = new \GuzzleHttp\Psr7\HttpFactory();
$client = new Client(
$accessToken,
@@ -100,76 +128,75 @@ class Api
$httpFactory,
$httpFactory,
self::API_BASE_URL,
self::API_VERSION,
null,
$this->logger,
);
}
$this->client = $client;
$this->modelFactory = $modelFactory ?? new ModelFactory();
$this->modelFactory = $modelFactory ?? new ModelFactory($this->logger);
$this->updateDispatcher = new UpdateDispatcher($this);
}
/**
* Performs a request to the Max Bot API.
*
* @param string $method The HTTP method (GET, POST, PATCH, etc.).
* @param string $uri The API endpoint (e.g., '/me', '/messages').
* @param array<string, mixed> $queryParams Query parameters for the request.
* @param array<string, mixed> $body The request body.
*
* @return array<string, mixed> The decoded JSON response as an associative array.
* @throws ClientApiException for API-level errors (4xx, 5xx).
* @throws NetworkException for network-related issues.
* @throws SerializationException for JSON encoding/decoding failures.
* @codeCoverageIgnore
*/
public function request(string $method, string $uri, array $queryParams = [], array $body = []): array
{
return $this->client->request($method, $uri, $queryParams, $body);
}
/**
* Gets the central update dispatcher instance. Use this to register your event and command handlers.
*
* @return UpdateDispatcher
* @codeCoverageIgnore
*/
public function getUpdateDispatcher(): UpdateDispatcher
{
return $this->updateDispatcher;
}
/**
* Creates a WebhookHandler instance, pre-configured with the necessary dependencies.
*
* @param string|null $secret The secret key for request verification.
* Should be the same one you used when calling the subscribe() method.
*
* @return WebhookHandler
*/
public function createWebhookHandler(?string $secret = null): WebhookHandler
{
return new WebhookHandler($this, $this->modelFactory, $secret);
return new WebhookHandler(
$this->updateDispatcher,
$this->modelFactory,
$this->logger,
$secret,
);
}
/**
* Parses an incoming webhook request and returns a single Update object.
* This is an alternative to the event-driven WebhookHandler::handle() method,
* allowing for manual processing of updates.
* Creates a LongPollingHandler instance, pre-configured for running a long-polling loop.
*
* @param string|null $secret The secret key to verify the request signature.
* @param ServerRequestInterface|null $request The PSR-7 request object. If null, it's created from globals.
*
* @return AbstractUpdate The parsed update object (e.g., MessageCreatedUpdate).
* @throws \ReflectionException
* @throws SecurityException
* @throws SerializationException
* @throws \LogicException
* @return LongPollingHandler
*/
public function getWebhookUpdate(?string $secret = null, ?ServerRequestInterface $request = null): AbstractUpdate
public function createLongPollingHandler(): LongPollingHandler
{
return $this->createWebhookHandler($secret)->getUpdate($request);
}
/**
* A simple way to process a single incoming webhook request using callbacks.
* This method creates a WebhookHandler, registers the provided callbacks, and processes the request.
*
* @param array<string, callable> $handlers An associative array where keys are UpdateType string values
* (e.g., UpdateType::MessageCreated->value) and values are handlers.
* @param string|null $secret The secret key for request verification.
* @param ServerRequestInterface|null $request The PSR-7 request object.
*
* @throws SecurityException
* @throws SerializationException
* @throws ReflectionException
* @throws LogicException
*/
public function handleWebhooks(
array $handlers,
?string $secret = null,
?ServerRequestInterface $request = null,
): void {
$webhookHandler = $this->createWebhookHandler($secret);
foreach ($handlers as $updateType => $callback) {
$updateType = UpdateType::tryFrom($updateType);
// @phpstan-ignore-next-line
if ($updateType && is_callable($callback)) {
$webhookHandler->addHandler($updateType, $callback);
}
}
$webhookHandler->handle($request);
return new LongPollingHandler(
$this,
$this->updateDispatcher,
$this->logger,
);
}
/**
@@ -209,58 +236,6 @@ class Api
);
}
/**
* Starts a long-polling loop to process updates using callbacks.
* This method will run indefinitely until the script is terminated.
*
* @param array<string, callable> $handlers An associative array where keys are UpdateType enums
* and values are the corresponding handler functions.
* @param int|null $timeout Timeout in seconds for long polling (0-90). Defaults to 90.
* @param int|null $marker Pass `null` to get updates you didn't get yet.
*/
public function handleUpdates(array $handlers, ?int $timeout = null, ?int $marker = null): void
{
// @phpstan-ignore-next-line
while (true) {
try {
$this->processUpdatesBatch($handlers, $timeout, $marker);
} catch (NetworkException $e) {
error_log("Network error: " . $e->getMessage());
sleep(5);
} catch (\Exception $e) {
error_log("An error occurred: " . $e->getMessage());
sleep(1);
}
}
}
/**
* Processes a single batch of updates. This is the core logic used by handleUpdates().
* Useful for custom loop implementations or for testing.
*
* @param array<string, callable> $handlers An associative array of update handlers.
* @param int|null $timeout Timeout for the getUpdates call.
* @param int|null $marker The marker for which updates to fetch.
*
* @throws ClientApiException
* @throws NetworkException
* @throws ReflectionException
* @throws SerializationException
*/
public function processUpdatesBatch(array $handlers, ?int $timeout, ?int &$marker = null): void
{
$updateList = $this->getUpdates(timeout: $timeout, marker: $marker);
foreach ($updateList->updates as $update) {
$handler = $handlers[$update->updateType->value] ?? null;
if ($handler) {
$handler($update, $this);
}
}
$marker = $updateList->marker;
}
/**
* Information about the current bot, identified by an access token.
*
@@ -348,7 +323,7 @@ class Api
}
/**
* Sends a message to a chat.
* Sends a message to a chat or user.
*
* @param int|null $userId Fill this parameter if you want to send message to user.
* @param int|null $chatId Fill this if you send message to chat.
@@ -381,25 +356,74 @@ class Api
'disable_link_preview' => $disableLinkPreview,
];
$body = [
'text' => $text,
'format' => $format?->value,
'notify' => $notify,
'link' => $link,
'attachments' => $attachments !== null ? array_map(
fn(AbstractModel $attachment) => $attachment->toArray(),
$attachments,
) : null,
];
$response = $this->client->request(
self::METHOD_POST,
self::ACTION_MESSAGES,
array_filter($query, fn($item) => null !== $item),
array_filter($body, fn($item) => null !== $item),
$this->buildNewMessageBody($text, $attachments, $format, $link, $notify),
);
return $this->modelFactory->createMessage($response['message']);
return $this->modelFactory->createMessageFromSendResponse($response);
}
/**
* Sends a message to a user.
*
* @param int|null $userId Fill this parameter if you want to send message to user.
* @param string|null $text Message text.
* @param AbstractAttachmentRequest[]|null $attachments Message attachments.
* @param MessageFormat|null $format Message format.
* @param MessageLink|null $link Link to message.
* @param bool $notify If false, chat participants would not be notified.
* @param bool $disableLinkPreview If false, server will not generate media preview for links in text.
*
* @return Message
* @throws ClientApiException
* @throws NetworkException
* @throws ReflectionException
* @throws SerializationException
* @codeCoverageIgnore
*/
public function sendUserMessage(
?int $userId = null,
?string $text = null,
?array $attachments = null,
?MessageFormat $format = null,
?MessageLink $link = null,
bool $notify = true,
bool $disableLinkPreview = false,
): Message {
return $this->sendMessage($userId, null, $text, $attachments, $format, $link, $notify, $disableLinkPreview);
}
/**
* Sends a message to a chat.
*
* @param int|null $chatId Fill this if you send message to chat.
* @param string|null $text Message text.
* @param AbstractAttachmentRequest[]|null $attachments Message attachments.
* @param MessageFormat|null $format Message format.
* @param MessageLink|null $link Link to message.
* @param bool $notify If false, chat participants would not be notified.
* @param bool $disableLinkPreview If false, server will not generate media preview for links in text.
*
* @return Message
* @throws ClientApiException
* @throws NetworkException
* @throws ReflectionException
* @throws SerializationException
* @codeCoverageIgnore
*/
public function sendChatMessage(
?int $chatId = null,
?string $text = null,
?array $attachments = null,
?MessageFormat $format = null,
?MessageLink $link = null,
bool $notify = true,
bool $disableLinkPreview = false,
): Message {
return $this->sendMessage(null, $chatId, $text, $attachments, $format, $link, $notify, $disableLinkPreview);
}
/**
@@ -421,6 +445,35 @@ class Api
);
}
/**
* Uploads a file to the specified URL.
*
* @param string $uploadUrl The target URL for the upload.
* @param resource $fileHandle A stream resource pointing to the file.
* @param string $fileName The desired file name for the upload.
*
* @return string The body of the final response from the server.
* @throws ClientApiException
* @throws NetworkException
* @throws SerializationException
* @throws RuntimeException
*/
public function uploadFile(string $uploadUrl, mixed $fileHandle, string $fileName): string
{
$stat = fstat($fileHandle);
if (!is_array($stat)) {
throw new RuntimeException('File handle is not a valid resource.');
}
rewind($fileHandle);
if ($stat['size'] < self::RESUMABLE_UPLOAD_THRESHOLD_BYTES) {
return $this->client->multipartUpload($uploadUrl, $fileHandle, $fileName);
}
return $this->client->resumableUpload($uploadUrl, $fileHandle, $fileName, $stat['size']);
}
/**
* A simplified method for uploading a file and getting the resulting attachment object.
*
@@ -449,27 +502,52 @@ class Api
$uploadEndpoint = $this->getUploadUrl($type);
$uploadResult = $this->client->upload(
$uploadEndpoint->url,
$fileHandle,
basename($filePath),
);
// For audio and video, the token is received *before* the upload
// The actual upload response is not JSON and can be ignored on success
if ($type === UploadType::Audio || $type === UploadType::Video) {
if (empty($uploadEndpoint->token)) {
throw new SerializationException(
"API did not return a pre-upload token for type '$type->value'."
);
}
fclose($fileHandle);
$this->uploadFile($uploadEndpoint->url, $fileHandle, basename($filePath));
fclose($fileHandle);
if (!isset($uploadResult['token'])) {
throw new SerializationException('Could not find "token" in upload server response.');
return match ($type) {
UploadType::Audio => new AudioAttachmentRequest($uploadEndpoint->token),
UploadType::Video => new VideoAttachmentRequest($uploadEndpoint->token),
};
}
return match ($type) {
UploadType::Image => PhotoAttachmentRequest::fromToken($uploadResult['token']),
UploadType::Video => new VideoAttachmentRequest($uploadResult['token']),
UploadType::Audio => new AudioAttachmentRequest($uploadResult['token']),
UploadType::File => new FileAttachmentRequest($uploadResult['token']), // @phpstan-ignore-line
default => throw new LogicException(
"Attachment creation for type '$type->value' is not yet implemented."
),
};
// For images and files, the token is in the response *after* the upload.
$responseBody = $this->uploadFile($uploadEndpoint->url, $fileHandle, basename($filePath));
fclose($fileHandle);
try {
$uploadResult = json_decode($responseBody, true, 512, JSON_THROW_ON_ERROR);
} catch (JsonException $e) {
throw new SerializationException('Failed to decode upload server response JSON.', 0, $e);
}
// Using switch because match expression arms cannot be code blocks.
switch ($type) {
case UploadType::Image:
$photoData = current($uploadResult['photos'] ?? []); // Get first photo from response
if (!isset($photoData['token'])) {
throw new SerializationException('Could not find "token" in photo upload response.');
}
return PhotoAttachmentRequest::fromToken($photoData['token']);
case UploadType::File:
if (!isset($uploadResult['token'])) {
throw new SerializationException('Could not find "token" in file upload response.');
}
return new FileAttachmentRequest($uploadResult['token']);
}
// @codeCoverageIgnoreStart
throw new LogicException("Attachment creation for type '$type->value' is not yet implemented."); // @phpstan-ignore-line
// @codeCoverageIgnoreEnd
}
/**
@@ -607,7 +685,6 @@ class Api
return null;
}
return $this->modelFactory->createMessage($response['message']);
}
@@ -779,7 +856,7 @@ class Api
[
'message_id' => $messageId,
'notify' => $notify,
]
],
)
);
}
@@ -824,7 +901,7 @@ class Api
int $chatId,
?array $userIds = null,
?int $marker = null,
?int $count = null
?int $count = null,
): ChatMembersList {
$query = [
'user_ids' => $userIds !== null ? implode(',', $userIds) : null,
@@ -853,7 +930,7 @@ class Api
* @throws ReflectionException
* @throws SerializationException
*/
public function deleteAdmins(int $chatId, int $userId): Result
public function deleteAdmin(int $chatId, int $userId): Result
{
return $this->modelFactory->createResult(
$this->client->request(
@@ -877,7 +954,7 @@ class Api
* @throws ReflectionException
* @throws SerializationException
*/
public function removeMember(int $chatId, int $userId, bool $block = false): Result
public function deleteMember(int $chatId, int $userId, bool $block = false): Result
{
return $this->modelFactory->createResult(
$this->client->request(
@@ -890,4 +967,238 @@ class Api
)
);
}
/**
* Sets the administrators for a chat.
*
* @param int $chatId The identifier of the chat.
* @param ChatAdmin[] $admins An array of ChatAdmin objects representing the users and their permissions.
*
* @return Result
* @throws ClientApiException
* @throws NetworkException
* @throws ReflectionException
* @throws SerializationException
*/
public function addAdmins(int $chatId, array $admins): Result
{
return $this->modelFactory->createResult(
$this->client->request(
self::METHOD_POST,
sprintf(self::ACTION_CHATS_MEMBERS_ADMINS, $chatId),
[],
['admins' => array_map(fn(ChatAdmin $admin) => $admin->toArray(), $admins)],
)
);
}
/**
* Adds members to a chat. The bot may require additional permissions.
*
* @param int $chatId The identifier of the chat.
* @param int[] $userIds An array of user identifiers to add to the chat.
*
* @return Result
* @throws ClientApiException
* @throws NetworkException
* @throws ReflectionException
* @throws SerializationException
*/
public function addMembers(int $chatId, array $userIds): Result
{
return $this->modelFactory->createResult(
$this->client->request(
self::METHOD_POST,
sprintf(self::ACTION_CHATS_MEMBERS, $chatId),
[],
['user_ids' => $userIds],
)
);
}
/**
* Sends an answer to a callback query. This should be called after a user clicks an inline button.
*
* @param string $callbackId The identifier of the callback query.
* @param string|null $notification A short text notification to show to the user.
* @param string|null $text If provided, the original message will be edited with this text.
* @param AbstractAttachmentRequest[]|null $attachments New attachments for the edited message.
* @param MessageLink|null $link New link for the edited message.
* @param MessageFormat|null $format Formatting for the new message text.
* @param bool $notify Notification setting for the edited message.
*
* @return Result
* @throws ClientApiException
* @throws NetworkException
* @throws ReflectionException
* @throws SerializationException
*/
public function answerOnCallback(
string $callbackId,
?string $notification = null,
?string $text = null,
?array $attachments = null,
?MessageLink $link = null,
?MessageFormat $format = null,
bool $notify = true,
): Result {
$answerBody = ['notification' => $notification];
if ($text !== null || $attachments !== null || $link !== null) {
$answerBody['message'] = $this->buildNewMessageBody($text, $attachments, $format, $link, $notify);
}
return $this->modelFactory->createResult(
$this->client->request(
self::METHOD_POST,
self::ACTION_ANSWERS,
['callback_id' => $callbackId],
array_filter($answerBody, fn($value) => $value !== null)
)
);
}
/**
* Edits a message that was previously sent by the bot.
* Note on attachments:
* - To leave attachments unchanged, pass `null` (default).
* - To remove all attachments, pass an empty array `[]`.
*
* @param string $messageId The identifier of the message to edit.
* @param string|null $text New message text.
* @param AbstractAttachmentRequest[]|null $attachments New message attachments.
* @param MessageFormat|null $format Formatting for the new message text.
* @param MessageLink|null $link New link for the edited message.
* @param bool $notify Notification setting for the edited message.
*
* @return Result
* @throws ClientApiException
* @throws NetworkException
* @throws ReflectionException
* @throws SerializationException
*/
public function editMessage(
string $messageId,
?string $text = null,
?array $attachments = null,
?MessageFormat $format = null,
?MessageLink $link = null,
bool $notify = true,
): Result {
return $this->modelFactory->createResult(
$this->client->request(
self::METHOD_PUT,
self::ACTION_MESSAGES,
['message_id' => $messageId],
$this->buildNewMessageBody($text, $attachments, $format, $link, $notify),
)
);
}
/**
* Edits the bot info.
*
* Example: editBotInfo(new BotPatch(name: 'New Bot Name', description: null));
*
* @param BotPatch $botPatch
*
* @return BotInfo
* @throws ClientApiException
* @throws NetworkException
* @throws ReflectionException
* @throws SerializationException
*/
public function editBotInfo(BotPatch $botPatch): BotInfo
{
return $this->modelFactory->createBotInfo(
$this->client->request(
self::METHOD_PATCH,
self::ACTION_ME,
[],
$botPatch->toArray(),
)
);
}
/**
* Edits chat info such as title, icon, etc.
* Instantiate ChatPatch with named arguments for the fields you want to change.
*
* Example:
* $patch = new ChatPatch(title: 'New Cool Title');
* $api->editChat(12345, $patch);
*
* @param int $chatId The identifier of the chat to edit.
* @param ChatPatch $chatPatch An object containing the fields to update.
*
* @return Chat
* @throws ClientApiException
* @throws NetworkException
* @throws ReflectionException
* @throws SerializationException
*/
public function editChat(int $chatId, ChatPatch $chatPatch): Chat
{
return $this->modelFactory->createChat(
$this->client->request(
self::METHOD_PATCH,
self::ACTION_CHATS . '/' . $chatId,
[],
$chatPatch->toArray(),
)
);
}
/**
* Returns detailed information about a video attachment, including playback URLs.
*
* @param string $videoToken The token of the video attachment.
*
* @return VideoAttachmentDetails
* @throws ClientApiException
* @throws NetworkException
* @throws ReflectionException
* @throws SerializationException
*/
public function getVideoAttachmentDetails(string $videoToken): VideoAttachmentDetails
{
return $this->modelFactory->createVideoAttachmentDetails(
$this->client->request(
self::METHOD_GET,
sprintf(self::ACTION_VIDEO_DETAILS, $videoToken),
)
);
}
/**
* A helper to build the 'NewMessageBody' array structure consistently.
*
* @param string|null $text
* @param AbstractAttachmentRequest[]|null $attachments
* @param MessageFormat|null $format
* @param MessageLink|null $link
* @param bool $notify
*
* @return array<string, mixed>
* @throws ReflectionException
*/
private function buildNewMessageBody(
?string $text,
?array $attachments,
?MessageFormat $format,
?MessageLink $link,
bool $notify,
): array {
$body = [
'text' => $text,
'format' => $format?->value,
'notify' => $notify,
'link' => $link,
'attachments' => $attachments !== null ? array_map(
fn(AbstractModel $attachment) => $attachment->toArray(),
$attachments,
) : null,
];
return array_filter($body, fn($item) => $item !== null);
}
}
+115 -9
View File
@@ -4,6 +4,7 @@ declare(strict_types=1);
namespace BushlanovDev\MaxMessengerBot;
use BushlanovDev\MaxMessengerBot\Exceptions\AttachmentNotReadyException;
use BushlanovDev\MaxMessengerBot\Exceptions\ForbiddenException;
use BushlanovDev\MaxMessengerBot\Exceptions\ClientApiException;
use BushlanovDev\MaxMessengerBot\Exceptions\MethodNotAllowedException;
@@ -19,6 +20,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 +38,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 +49,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.');
@@ -55,13 +61,20 @@ final readonly class Client implements ClientApiInterface
*/
public function request(string $method, string $uri, array $queryParams = [], array $body = []): array
{
$queryParams['access_token'] = $this->accessToken;
if (!empty($this->apiVersion)) {
$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);
$request = $this->requestFactory
->createRequest($method, $fullUrl)
->withHeader('Authorization', $this->accessToken);
if (!empty($body)) {
try {
@@ -79,6 +92,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 +103,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 +125,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();
@@ -123,6 +145,7 @@ final readonly class Client implements ClientApiInterface
$request = $this->requestFactory
->createRequest('POST', $uri)
->withHeader('Content-Type', 'multipart/form-data; boundary=' . $boundary)
->withHeader('Authorization', $this->accessToken)
->withBody($bodyStream);
try {
@@ -133,13 +156,71 @@ 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}")
->withHeader('Authorization', $this->accessToken);
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,13 +242,38 @@ 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),
404 => new NotFoundException($errorMessage, $errorCode, $response),
405 => new MethodNotAllowedException($errorMessage, $errorCode, $response),
429 => new RateLimitExceededException($errorMessage, $errorCode, $response),
default => new ClientApiException($errorMessage, $errorCode, $response, $statusCode),
default => $this->mapErrorCodeToException($errorMessage, $errorCode, $response, $statusCode),
};
}
/**
* @param string $message
* @param string $errorCode
* @param ResponseInterface $response
* @param int|null $httpStatusCode
*
* @return ClientApiException
*/
private function mapErrorCodeToException(
string $message,
string $errorCode,
ResponseInterface $response,
?int $httpStatusCode = null,
): ClientApiException {
return match ($errorCode) {
'attachment.not.ready' => new AttachmentNotReadyException($message, $errorCode, $response, $httpStatusCode),
default => new ClientApiException($message, $errorCode, $response, $httpStatusCode),
};
}
}
+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;
}
+1 -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';
+5
View File
@@ -15,4 +15,9 @@ enum ChatAdminPermission: string
case ChangeChatInfo = 'change_chat_info';
case PinMessage = 'pin_message';
case Write = 'write';
case CanCall = 'can_call';
case EditLink = 'edit_link';
case PostEditDeleteMessage = 'post_edit_delete_message';
case EditMessage = 'edit_message';
case DeleteMessage = 'delete_message';
}
@@ -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
@@ -15,9 +15,14 @@ enum UpdateType: string
case MessageRemoved = 'message_removed';
case BotAdded = 'bot_added';
case BotRemoved = 'bot_removed';
case DialogMuted = 'dialog_muted';
case DialogUnmuted = 'dialog_unmuted';
case DialogCleared = 'dialog_cleared';
case DialogRemoved = 'dialog_removed';
case UserAdded = 'user_added';
case UserRemoved = 'user_removed';
case BotStarted = 'bot_started';
case BotStopped = 'bot_stopped';
case ChatTitleChanged = 'chat_title_changed';
case MessageChatCreated = 'message_chat_created';
}
@@ -0,0 +1,13 @@
<?php
declare(strict_types=1);
namespace BushlanovDev\MaxMessengerBot\Exceptions;
/**
* Exception thrown when an attachment is not yet ready for use.
* This typically occurs when trying to use an attachment that is still being processed.
*/
class AttachmentNotReadyException extends ClientApiException
{
}
-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';
}
}
+428
View File
@@ -0,0 +1,428 @@
<?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.
*/
readonly class MaxBotManager
{
/**
* @param Container $container
* @param Api $api
* @param UpdateDispatcher $dispatcher
*/
public function __construct(
private Container $container,
private Api $api,
private 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 dialog mute handler.
*
* @param callable|string $handler Can be a closure, callable, or Laravel container binding.
*
* @throws BindingResolutionException
* @codeCoverageIgnore
*/
public function onDialogMuted(callable|string $handler): void
{
$this->dispatcher->onDialogMuted($this->resolveHandler($handler));
}
/**
* Register a dialog unmute handler.
*
* @param callable|string $handler Can be a closure, callable, or Laravel container binding.
*
* @throws BindingResolutionException
* @codeCoverageIgnore
*/
public function onDialogUnmuted(callable|string $handler): void
{
$this->dispatcher->onDialogUnmuted($this->resolveHandler($handler));
}
/**
* Register a dialog cleared handler.
*
* @param callable|string $handler Can be a closure, callable, or Laravel container binding.
*
* @throws BindingResolutionException
* @codeCoverageIgnore
*/
public function onDialogCleared(callable|string $handler): void
{
$this->dispatcher->onDialogCleared($this->resolveHandler($handler));
}
/**
* Register a dialog removed handler.
*
* @param callable|string $handler Can be a closure, callable, or Laravel container binding.
*
* @throws BindingResolutionException
* @codeCoverageIgnore
*/
public function onDialogRemoved(callable|string $handler): void
{
$this->dispatcher->onDialogRemoved($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 bot stopped handler.
*
* @param callable|string $handler Can be a closure, callable, or Laravel container binding.
*
* @throws BindingResolutionException
* @codeCoverageIgnore
*/
public function onBotStopped(callable|string $handler): void
{
$this->dispatcher->onBotStopped($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;
}
}
+214
View File
@@ -0,0 +1,214 @@
<?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://platform-api.max.ru'),
$config->get('maxbot.api_version'),
$logger,
);
});
$this->app->singleton(ModelFactory::class, function (Application $app) {
/** @var Config $config */
$config = $app->make(Config::class);
$logger = $config->get('maxbot.logging.enabled', false)
? $app->make(LoggerInterface::class)
: new NullLogger();
return new ModelFactory($logger);
});
$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.'
);
}
$logger = $config->get('maxbot.logging.enabled', false)
? $app->make(LoggerInterface::class)
: new NullLogger();
return new Api(
$accessToken,
$app->make(ClientApiInterface::class),
$app->make(ModelFactory::class),
$logger,
);
});
$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');
$logger = $config->get('maxbot.logging.enabled', false)
? $app->make(LoggerInterface::class)
: new NullLogger();
return new WebhookHandler(
$app->make(UpdateDispatcher::class),
$app->make(ModelFactory::class),
$logger,
$secret,
);
});
$this->app->bind(LongPollingHandler::class, function (Application $app) {
/** @var Config $config */
$config = $app->make(Config::class);
$logger = $config->get('maxbot.logging.enabled', false)
? $app->make(LoggerInterface::class)
: new NullLogger();
return new LongPollingHandler(
$app->make(Api::class),
$app->make(UpdateDispatcher::class),
$logger,
);
});
$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);
}
}
}
+241 -2
View File
@@ -4,13 +4,50 @@ 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\MessageButton;
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\FileAttachment;
use BushlanovDev\MaxMessengerBot\Models\Attachments\InlineKeyboardAttachment;
use BushlanovDev\MaxMessengerBot\Models\Attachments\LocationAttachment;
use BushlanovDev\MaxMessengerBot\Models\Attachments\PhotoAttachment;
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;
@@ -18,7 +55,12 @@ use BushlanovDev\MaxMessengerBot\Models\Updates\AbstractUpdate;
use BushlanovDev\MaxMessengerBot\Models\Updates\BotAddedToChatUpdate;
use BushlanovDev\MaxMessengerBot\Models\Updates\BotRemovedFromChatUpdate;
use BushlanovDev\MaxMessengerBot\Models\Updates\BotStartedUpdate;
use BushlanovDev\MaxMessengerBot\Models\Updates\BotStoppedUpdate;
use BushlanovDev\MaxMessengerBot\Models\Updates\ChatTitleChangedUpdate;
use BushlanovDev\MaxMessengerBot\Models\Updates\DialogClearedUpdate;
use BushlanovDev\MaxMessengerBot\Models\Updates\DialogMutedUpdate;
use BushlanovDev\MaxMessengerBot\Models\Updates\DialogRemovedUpdate;
use BushlanovDev\MaxMessengerBot\Models\Updates\DialogUnmutedUpdate;
use BushlanovDev\MaxMessengerBot\Models\Updates\MessageCallbackUpdate;
use BushlanovDev\MaxMessengerBot\Models\Updates\MessageChatCreatedUpdate;
use BushlanovDev\MaxMessengerBot\Models\Updates\MessageCreatedUpdate;
@@ -27,14 +69,27 @@ 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 Psr\Log\LoggerInterface;
use Psr\Log\NullLogger;
use ReflectionException;
/**
* Creates DTOs from raw associative arrays returned by the API client.
*/
class ModelFactory
readonly class ModelFactory
{
private LoggerInterface $logger;
/**
* @param LoggerInterface|null $logger PSR LoggerInterface.
*/
public function __construct(?LoggerInterface $logger = null)
{
$this->logger = $logger ?? new NullLogger();
}
/**
* Simple response to request.
*
@@ -89,6 +144,33 @@ class ModelFactory
: [];
}
/**
* Creates a Message from the specific response structure of the sendMessage endpoint.
*
* @param array<string, mixed> $data The raw response from the client.
*
* @return Message
* @throws ReflectionException
*/
public function createMessageFromSendResponse(array $data): Message
{
$messageData = $data['message'];
$topLevelData = [
'chat_id' => $data['chat_id'] ?? null,
'recipient_id' => $data['recipient_id'] ?? null,
'message_id' => $data['message_id'] ?? null,
];
$messageData = array_merge($messageData, array_filter($topLevelData, fn($value) => $value !== null));
if (isset($messageData['message']) && is_array($messageData['message'])) {
$messageData['body'] = $messageData['message'];
unset($messageData['message']);
}
return $this->createMessage($messageData);
}
/**
* Message.
*
@@ -99,6 +181,10 @@ 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);
}
@@ -116,6 +202,111 @@ class ModelFactory
: [];
}
/**
* 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::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::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::Location => LocationAttachment::fromArray($data),
AttachmentType::Share => ShareAttachment::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),
InlineButtonType::Message => MessageButton::fromArray($data),
default => throw new LogicException(
'Unknown or unsupported inline button type: ' . ($data['type'] ?? 'none')
),
};
}
/**
* Endpoint you should upload to your binaries.
*
@@ -157,7 +348,11 @@ class ModelFactory
if (isset($data['updates']) && is_array($data['updates'])) {
foreach ($data['updates'] as $updateData) {
// Here we delegate the creation of a specific update to another factory method
$updateObjects[] = $this->createUpdate($updateData);
try {
$updateObjects[] = $this->createUpdate($updateData);
} catch (LogicException $e) {
$this->logger->debug($e->getMessage(), ['payload' => $updateData, 'exception' => $e]);
}
}
}
@@ -185,9 +380,14 @@ class ModelFactory
UpdateType::MessageRemoved => MessageRemovedUpdate::fromArray($data),
UpdateType::BotAdded => BotAddedToChatUpdate::fromArray($data),
UpdateType::BotRemoved => BotRemovedFromChatUpdate::fromArray($data),
UpdateType::DialogMuted => DialogMutedUpdate::fromArray($data),
UpdateType::DialogUnmuted => DialogUnmutedUpdate::fromArray($data),
UpdateType::DialogCleared => DialogClearedUpdate::fromArray($data),
UpdateType::DialogRemoved => DialogRemovedUpdate::fromArray($data),
UpdateType::UserAdded => UserAddedToChatUpdate::fromArray($data),
UpdateType::UserRemoved => UserRemovedFromChatUpdate::fromArray($data),
UpdateType::BotStarted => BotStartedUpdate::fromArray($data),
UpdateType::BotStopped => BotStoppedUpdate::fromArray($data),
UpdateType::ChatTitleChanged => ChatTitleChangedUpdate::fromArray($data),
UpdateType::MessageChatCreated => MessageChatCreatedUpdate::fromArray($data),
default => throw new LogicException(
@@ -234,4 +434,43 @@ class ModelFactory
{
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;
}
}
@@ -4,18 +4,16 @@ declare(strict_types=1);
namespace BushlanovDev\MaxMessengerBot\Models;
/**
* User who sent this message.
*/
final readonly class Sender extends AbstractModel
abstract readonly class AbstractUser 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 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 int $lastActivityTime Time of last user activity in Max (Unix timestamp in milliseconds).
* Can be outdated if user disabled its "online" status in settings.
*/
public function __construct(
public int $userId,
@@ -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;
}
@@ -0,0 +1,21 @@
<?php
declare(strict_types=1);
namespace BushlanovDev\MaxMessengerBot\Models\Attachments\Buttons\Inline;
use BushlanovDev\MaxMessengerBot\Enums\InlineButtonType;
/**
* Button send text in chat from user.
*/
final readonly class MessageButton extends AbstractInlineButton
{
/**
* @param string $text Text sending in chat from user.
*/
public function __construct(string $text)
{
parent::__construct(InlineButtonType::Message, $text);
}
}
@@ -2,28 +2,31 @@
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;
public ?string $payload;
/**
* @param string $text Visible button text (1 to 128 characters).
* @param string|null $webApp The public name (username) of the bot or a link to it, whose mini-application should be launched.
* @param int|null $contactId The ID of the bot whose mini-app should be launched.
* @param string|null $payload Init param which would be passed in mini-application initData (1 to 512 characters, allowed A-Z, a-z, 0-9, _(underscore) , - (minus) ).
*/
public function __construct(string $text, ?string $webApp = null, ?int $contactId = null)
public function __construct(string $text, ?string $webApp = null, ?int $contactId = null, ?string $payload = null)
{
parent::__construct(ButtonType::OpenApp, $text);
parent::__construct(InlineButtonType::OpenApp, $text);
$this->webApp = $webApp;
$this->contactId = $contactId;
$this->payload = $payload;
}
}
@@ -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);
}
}
+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\UserWithPhoto;
/**
* Payload of a contact attachment.
*/
final readonly class ContactAttachmentPayload extends AbstractModel
{
/**
* @param string|null $vcfInfo User info in VCF format.
* @param UserWithPhoto|null $maxInfo User info if the contact is a Max user.
*/
public function __construct(
public ?string $vcfInfo,
public ?UserWithPhoto $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,
) {
}
}
@@ -23,9 +23,9 @@ final readonly class PhotoAttachmentRequestPayload extends AbstractAttachmentReq
#[ArrayOf(PhotoToken::class)]
public ?array $photos = null,
) {
if (count(array_filter([$this->url, $this->token, $this->photos])) !== 1) {
if ($this->url === null && $this->token === null && $this->photos === null) {
throw new InvalidArgumentException(
'Provide exactly one of "url", "token", or "photos" for PhotoAttachmentRequestPayload.'
'Provide one of "url", "token", or "photos" for PhotoAttachmentRequestPayload.'
);
}
}
@@ -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)
{
}
}
@@ -19,9 +19,9 @@ final readonly class ShareAttachmentRequestPayload extends AbstractAttachmentReq
public ?string $url = null,
public ?string $token = null,
) {
if (count(array_filter([$this->url, $this->token])) !== 1) {
if ($this->url === null && $this->token === null) {
throw new InvalidArgumentException(
'Provide exactly one of "url" or "token" for ShareAttachmentRequestPayload.'
'Provide one of "url" or "token" for ShareAttachmentRequestPayload.'
);
}
}
@@ -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);
}
}
@@ -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,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);
}
}
+8 -7
View File
@@ -9,7 +9,7 @@ use BushlanovDev\MaxMessengerBot\Attributes\ArrayOf;
/**
* Information about the current bot.
*/
final readonly class BotInfo extends AbstractModel
final readonly class BotInfo extends AbstractUser
{
/**
* @param int $userId ID user.
@@ -24,17 +24,18 @@ final readonly class BotInfo extends AbstractModel
* @param BotCommand[]|null $commands Commands supported by the bot (up to 32 elements).
*/
public function __construct(
public int $userId,
public string $firstName,
public ?string $lastName,
public ?string $username,
public bool $isBot,
public int $lastActivityTime,
int $userId,
string $firstName,
?string $lastName,
?string $username,
bool $isBot,
int $lastActivityTime,
public ?string $description,
public ?string $avatarUrl,
public ?string $fullAvatarUrl,
#[ArrayOf(BotCommand::class)]
public ?array $commands,
) {
parent::__construct($userId, $firstName, $lastName, $username, $isBot, $lastActivityTime);
}
}
+23
View File
@@ -0,0 +1,23 @@
<?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(first_name: 'New Bot Name', description: null);
*
* @property-read string|null $first_name
* @property-read string|null $last_name
* @property-read string|null $description
* @property-read BotCommand[]|null $commands
* @property-read PhotoAttachmentRequestPayload|null $photo
* @property-read string|null $name @deprecated Use first_name
*/
final readonly class BotPatch extends AbstractPatchModel
{
}
+2 -2
View File
@@ -13,13 +13,13 @@ final readonly class Callback extends AbstractModel
* @param int $timestamp Unix-time when user pressed the button.
* @param string $callbackId Identifier of the callback, unique for the message.
* @param string $payload Payload from the pressed button.
* @param User $user User who pressed the button.
* @param UserWithPhoto $user User who pressed the button.
*/
public function __construct(
public int $timestamp,
public string $callbackId,
public string $payload,
public User $user,
public UserWithPhoto $user,
) {
}
}
+4 -2
View File
@@ -24,10 +24,11 @@ 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.
* @param array<string, int>|null $participants List of participants in chat. Returned only when single chat is requested.
*/
public function __construct(
public int $chatId,
@@ -41,10 +42,11 @@ 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,
public ?array $participants,
) {
}
}
+27
View File
@@ -0,0 +1,27 @@
<?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.
* @param string|null $alias Alias of the user.
*/
public function __construct(
public int $userId,
#[ArrayOf(ChatAdminPermission::class)]
public array $permissions,
public ?string $alias = null,
) {
}
}
+10 -7
View File
@@ -10,7 +10,7 @@ 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
final readonly class ChatMember extends AbstractUser
{
/**
* @param int $userId User's identifier.
@@ -27,14 +27,15 @@ final readonly class ChatMember extends AbstractModel
* @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.
* @param string|null $alias Alias of the user.
*/
public function __construct(
public int $userId,
public string $firstName,
public ?string $lastName,
public ?string $username,
public bool $isBot,
public int $lastActivityTime,
int $userId,
string $firstName,
?string $lastName,
?string $username,
bool $isBot,
int $lastActivityTime,
public ?string $description,
public ?string $avatarUrl,
public ?string $fullAvatarUrl,
@@ -44,6 +45,8 @@ final readonly class ChatMember extends AbstractModel
public int $joinTime,
#[ArrayOf(ChatAdminPermission::class)]
public ?array $permissions,
public ?string $alias,
) {
parent::__construct($userId, $firstName, $lastName, $username, $isBot, $lastActivityTime);
}
}
+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 UserWithPhoto|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 ?UserWithPhoto $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);
}
}
+14 -4
View File
@@ -11,17 +11,27 @@ 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 UserWithPhoto|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.
* @param int|null $chatId Chat identifier.
* @param int|null $recipientId User identifier, if message was sent to user.
* @param string|null $messageId Unique identifier of message.
*/
public function __construct(
public int $timestamp,
public MessageBody $body,
public Recipient $recipient,
public ?Sender $sender,
public ?MessageBody $body,
public ?UserWithPhoto $sender,
public ?string $url,
public ?LinkedMessage $link,
public ?MessageStat $stat,
public ?int $chatId = null,
public ?int $recipientId = null,
public ?string $messageId = null,
) {
}
}
+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)
{
}
}
+3 -3
View File
@@ -5,7 +5,7 @@ declare(strict_types=1);
namespace BushlanovDev\MaxMessengerBot\Models\Updates;
use BushlanovDev\MaxMessengerBot\Enums\UpdateType;
use BushlanovDev\MaxMessengerBot\Models\User;
use BushlanovDev\MaxMessengerBot\Models\UserWithPhoto;
/**
* You will receive this update when the bot has been added to a chat.
@@ -15,13 +15,13 @@ final readonly class BotAddedToChatUpdate extends AbstractUpdate
/**
* @param int $timestamp Unix-time when the event has occurred.
* @param int $chatId Chat ID where the bot was added.
* @param User $user User who added the bot to the chat.
* @param UserWithPhoto $user User who added the bot to the chat.
* @param bool $isChannel Indicates whether the bot has been added to a channel or not.
*/
public function __construct(
int $timestamp,
public int $chatId,
public User $user,
public UserWithPhoto $user,
public bool $isChannel,
) {
parent::__construct(UpdateType::BotAdded, $timestamp);
@@ -5,7 +5,7 @@ declare(strict_types=1);
namespace BushlanovDev\MaxMessengerBot\Models\Updates;
use BushlanovDev\MaxMessengerBot\Enums\UpdateType;
use BushlanovDev\MaxMessengerBot\Models\User;
use BushlanovDev\MaxMessengerBot\Models\UserWithPhoto;
/**
* You will receive this update when the bot has been removed from a chat.
@@ -15,13 +15,13 @@ final readonly class BotRemovedFromChatUpdate extends AbstractUpdate
/**
* @param int $timestamp Unix-time when the event has occurred.
* @param int $chatId Chat identifier the bot was removed from.
* @param User $user User who removed the bot from the chat.
* @param UserWithPhoto $user User who removed the bot from the chat.
* @param bool $isChannel Indicates whether the bot has been removed from a channel or not.
*/
public function __construct(
int $timestamp,
public int $chatId,
public User $user,
public UserWithPhoto $user,
public bool $isChannel,
) {
parent::__construct(UpdateType::BotRemoved, $timestamp);
+3 -3
View File
@@ -5,7 +5,7 @@ declare(strict_types=1);
namespace BushlanovDev\MaxMessengerBot\Models\Updates;
use BushlanovDev\MaxMessengerBot\Enums\UpdateType;
use BushlanovDev\MaxMessengerBot\Models\User;
use BushlanovDev\MaxMessengerBot\Models\UserWithPhoto;
/**
* Bot gets this type of update as soon as user pressed `Start` button.
@@ -15,14 +15,14 @@ final readonly class BotStartedUpdate extends AbstractUpdate
/**
* @param int $timestamp Unix-time when event has occurred.
* @param int $chatId Dialog identifier where event has occurred.
* @param User $user User pressed the 'Start' button.
* @param UserWithPhoto $user User pressed the 'Start' button.
* @param string|null $payload Additional data from deep-link passed on bot startup.
* @param string|null $userLocale Current user locale in IETF BCP 47 format.
*/
public function __construct(
int $timestamp,
public int $chatId,
public User $user,
public UserWithPhoto $user,
public ?string $payload,
public ?string $userLocale,
) {
+29
View File
@@ -0,0 +1,29 @@
<?php
declare(strict_types=1);
namespace BushlanovDev\MaxMessengerBot\Models\Updates;
use BushlanovDev\MaxMessengerBot\Enums\UpdateType;
use BushlanovDev\MaxMessengerBot\Models\UserWithPhoto;
/**
* The bot receives this type of update as soon as the user stops the bot.
*/
final readonly class BotStoppedUpdate extends AbstractUpdate
{
/**
* @param int $timestamp Unix-time when event has occurred.
* @param int $chatId Dialog identifier where event has occurred.
* @param UserWithPhoto $user User pressed the 'Start' button.
* @param string|null $userLocale Current user locale in IETF BCP 47 format.
*/
public function __construct(
int $timestamp,
public int $chatId,
public UserWithPhoto $user,
public ?string $userLocale,
) {
parent::__construct(UpdateType::BotStopped, $timestamp);
}
}
@@ -5,7 +5,7 @@ declare(strict_types=1);
namespace BushlanovDev\MaxMessengerBot\Models\Updates;
use BushlanovDev\MaxMessengerBot\Enums\UpdateType;
use BushlanovDev\MaxMessengerBot\Models\User;
use BushlanovDev\MaxMessengerBot\Models\UserWithPhoto;
/**
* Bot gets this type of update as soon as the title has been changed in a chat.
@@ -15,13 +15,13 @@ final readonly class ChatTitleChangedUpdate extends AbstractUpdate
/**
* @param int $timestamp Unix-time when the event has occurred.
* @param int $chatId Chat identifier where the event has occurred.
* @param User $user User who changed the title.
* @param UserWithPhoto $user User who changed the title.
* @param string $title The new title.
*/
public function __construct(
int $timestamp,
public int $chatId,
public User $user,
public UserWithPhoto $user,
public string $title,
) {
parent::__construct(UpdateType::ChatTitleChanged, $timestamp);
@@ -0,0 +1,29 @@
<?php
declare(strict_types=1);
namespace BushlanovDev\MaxMessengerBot\Models\Updates;
use BushlanovDev\MaxMessengerBot\Enums\UpdateType;
use BushlanovDev\MaxMessengerBot\Models\UserWithPhoto;
/**
* Event clearing dialog history.
*/
final readonly class DialogClearedUpdate extends AbstractUpdate
{
/**
* @param int $timestamp Unix-time when event has occurred.
* @param int $chatId Dialog identifier where event has occurred.
* @param UserWithPhoto $user User pressed the 'Start' button.
* @param string|null $userLocale Current user locale in IETF BCP 47 format.
*/
public function __construct(
int $timestamp,
public int $chatId,
public UserWithPhoto $user,
public ?string $userLocale,
) {
parent::__construct(UpdateType::DialogCleared, $timestamp);
}
}
+31
View File
@@ -0,0 +1,31 @@
<?php
declare(strict_types=1);
namespace BushlanovDev\MaxMessengerBot\Models\Updates;
use BushlanovDev\MaxMessengerBot\Enums\UpdateType;
use BushlanovDev\MaxMessengerBot\Models\UserWithPhoto;
/**
* Event when a user mutes a conversation with a bot.
*/
final readonly class DialogMutedUpdate extends AbstractUpdate
{
/**
* @param int $timestamp Unix-time when event has occurred.
* @param int $chatId Dialog identifier where event has occurred.
* @param UserWithPhoto $user User pressed the 'Start' button.
* @param int|null $mutedUntil The time in Unix format before which the dialog was disabled.
* @param string|null $userLocale Current user locale in IETF BCP 47 format.
*/
public function __construct(
int $timestamp,
public int $chatId,
public UserWithPhoto $user,
public ?int $mutedUntil,
public ?string $userLocale,
) {
parent::__construct(UpdateType::DialogMuted, $timestamp);
}
}
@@ -0,0 +1,29 @@
<?php
declare(strict_types=1);
namespace BushlanovDev\MaxMessengerBot\Models\Updates;
use BushlanovDev\MaxMessengerBot\Enums\UpdateType;
use BushlanovDev\MaxMessengerBot\Models\UserWithPhoto;
/**
* Event deleting a chat.
*/
final readonly class DialogRemovedUpdate extends AbstractUpdate
{
/**
* @param int $timestamp Unix-time when event has occurred.
* @param int $chatId Dialog identifier where event has occurred.
* @param UserWithPhoto $user User pressed the 'Start' button.
* @param string|null $userLocale Current user locale in IETF BCP 47 format.
*/
public function __construct(
int $timestamp,
public int $chatId,
public UserWithPhoto $user,
public ?string $userLocale,
) {
parent::__construct(UpdateType::DialogRemoved, $timestamp);
}
}

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