PHP code example of dizvestnov / laravel-max-bot
1. Go to this page and download the library: Download dizvestnov/laravel-max-bot library . Choose the download type require .
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
dizvestnov / laravel-max-bot example snippets
return [
'token' => env('MAX_BOT_TOKEN', ''),
'http' => [
'base_uri' => env('MAX_BOT_BASE_URI', 'https://platform-api.max.ru'),
'timeout' => (int) env('MAX_BOT_TIMEOUT', 30),
'retry' => [
'times' => 3,
'sleep' => 100, // базовая задержка в мс (экспоненциальный backoff)
],
],
'webhook' => [
'secret' => env('MAX_BOT_WEBHOOK_SECRET', null),
'version' => env('MAX_BOT_WEBHOOK_VERSION', null),
'route' => [
'enabled' => true,
'path' => env('MAX_BOT_WEBHOOK_PATH', 'max-bot/webhook'),
'middleware' => ['api'],
],
],
'queue' => [
'enabled' => (bool) env('MAX_BOT_QUEUE_ENABLED', false),
'connection' => env('MAX_BOT_QUEUE_CONNECTION', null),
'queue' => env('MAX_BOT_QUEUE_NAME', 'default'),
],
];
use Dizvestnov\LaravelMaxBot\Messages\OutgoingMessage;
// Простое текстовое сообщение пользователю
OutgoingMessage::create('Привет!')
->to($userId)
->send();
// Сообщение в чат
OutgoingMessage::create('Всем привет!')
->inChat($chatId)
->send();
// Markdown-форматирование
OutgoingMessage::create('**Жирный** и _курсив_')
->to($userId)
->markdown()
->send();
// HTML-форматирование
OutgoingMessage::create('<b>Жирный</b>')
->to($userId)
->html()
->send();
// Ответ на конкретное сообщение
OutgoingMessage::create('Ответ')
->to($userId)
->replyTo($messageId)
->send();
use Dizvestnov\LaravelMaxBot\Facades\MaxBot;
MaxBot::sendMessage([
'recipient' => ['user_id' => $userId],
'text' => 'Привет!',
]);
use Dizvestnov\LaravelMaxBot\Keyboard;
use Dizvestnov\LaravelMaxBot\Buttons\CallbackButton;
use Dizvestnov\LaravelMaxBot\Buttons\LinkButton;
use Dizvestnov\LaravelMaxBot\Buttons\RequestContactButton;
use Dizvestnov\LaravelMaxBot\Buttons\RequestGeoLocationButton;
$keyboard = Keyboard::make()
->row(
CallbackButton::make('Да', 'answer_yes'),
CallbackButton::make('Нет', 'answer_no'),
)
->row(
LinkButton::make('Наш сайт', 'https://example.com'),
)
->row(
RequestContactButton::make('Поделиться контактом'),
RequestGeoLocationButton::make('Отправить геолокацию'),
);
OutgoingMessage::create('Выберите вариант:')
->to($userId)
->withKeyboard($keyboard)
->send();
use Dizvestnov\LaravelMaxBot\Events\MessageReceived;
use Dizvestnov\LaravelMaxBot\Events\CallbackReceived;
use Dizvestnov\LaravelMaxBot\Events\BotStarted;
protected $listen = [
MessageReceived::class => [
App\Listeners\HandleMessage::class,
],
CallbackReceived::class => [
App\Listeners\HandleCallback::class,
],
BotStarted::class => [
App\Listeners\WelcomeNewUser::class,
],
];
namespace App\Listeners;
use Dizvestnov\LaravelMaxBot\Events\MessageReceived;
use Dizvestnov\LaravelMaxBot\Messages\OutgoingMessage;
class HandleMessage
{
public function handle(MessageReceived $event): void
{
$text = $event->getText();
$userId = $event->getSenderId();
OutgoingMessage::create("Вы написали: {$text}")
->to($userId)
->send();
}
}
$event->getUpdateType(); // тип обновления
$event->getChatId(); // ID чата (или null)
$event->getTimestamp(); // unix-timestamp
$event->update; // исходный массив обновления
$event->getText(); // текст сообщения
$event->getSenderId(); // ID отправителя
$event->getMessage(); // полный массив сообщения
use Dizvestnov\LaravelMaxBot\Conversation\StateManager;
class RegistrationListener
{
public function __construct(private StateManager $state) {}
public function handle(MessageReceived $event): void
{
$userId = $event->getSenderId();
$step = $this->state->getState($userId);
if ($step === null) {
$this->state->setState($userId, 'ask_name');
OutgoingMessage::create('Как вас зовут?')->to($userId)->send();
return;
}
if ($step === 'ask_name') {
$this->state->mergeData($userId, ['name' => $event->getText()]);
$this->state->setState($userId, 'ask_email');
OutgoingMessage::create('Ваш email?')->to($userId)->send();
return;
}
if ($step === 'ask_email') {
$data = $this->state->getData($userId);
// $data['name'] и $event->getText() — готово
$this->state->clearState($userId);
OutgoingMessage::create('Регистрация завершена!')->to($userId)->send();
}
}
}
$state->getState(int $userId): ?string
$state->setState(int $userId, string $state, int $ttl = 3600): void
$state->clearState(int $userId): void
$state->getData(int $userId): array
$state->setData(int $userId, array $data, int $ttl = 3600): void
$state->mergeData(int $userId, array $data): void
use Dizvestnov\LaravelMaxBot\Contracts\MaxBotClientInterface;
class MyService
{
public function __construct(private MaxBotClientInterface $bot) {}
}
MaxBot::getBotInfo();
MaxBot::editBotInfo(['name' => 'Новое имя']);
MaxBot::sendMessage([...]);
MaxBot::editMessage([...]);
MaxBot::deleteMessage($messageId);
MaxBot::getMessage($messageId);
MaxBot::getMessages(['chat_id' => $chatId]);
MaxBot::answerOnCallback(['callback_id' => $id, 'text' => 'OK']);
MaxBot::getChats();
MaxBot::getChat($chatId);
MaxBot::editChat($chatId, ['title' => 'Новое название']);
MaxBot::deleteChat($chatId);
MaxBot::sendAction($chatId, 'typing');
MaxBot::getPinnedMessage($chatId);
MaxBot::pinMessage($chatId, ['message_id' => $messageId]);
MaxBot::unpinMessage($chatId);
MaxBot::getMembership($chatId);
MaxBot::leaveChat($chatId);
MaxBot::getAdmins($chatId);
MaxBot::addAdmins($chatId, [$userId]);
MaxBot::deleteAdmin($chatId, $userId);
MaxBot::getMembers($chatId);
MaxBot::addMembers($chatId, [$userId]);
MaxBot::deleteMember($chatId, $userId);
MaxBot::getSubscriptions();
MaxBot::subscribe(['url' => 'https://...', 'secret' => '...']);
MaxBot::unsubscribe();
MaxBot::getUpdates(['limit' => 10]);
MaxBot::getUploadUrl('image');
MaxBot::getVideoDetails($videoToken);
use Dizvestnov\LaravelMaxBot\Contracts\MaxBotClientInterface;
public function test_bot_replies(): void
{
$this->mock(MaxBotClientInterface::class, function ($mock) {
$mock->shouldReceive('sendMessage')
->once()
->with(\Mockery::on(fn($p) => $p['text'] === 'Привет!'))
->andReturn(['message_id' => 'abc123']);
});
// вызвать логику, которая отправляет сообщение...
}
bash
php artisan vendor:publish --tag=max-bot-config
bash
php artisan max-bot:webhook:set https://yourdomain.com/max-bot/webhook
bash
php artisan max-bot:poll