1. Go to this page and download the library: Download gagins/phpmaxbot 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/ */
gagins / phpmaxbot example snippets
PHPMaxBot\Helpers\Keyboard;
$token = 'your-bot-token';
$bot = new PHPMaxBot($token);
// Обработка команды /start
$bot->command('start', function() {
return Bot::sendMessage('Привет! Я бот на MAX мессенджере.');
});
// Обработка команды /help
$bot->command('help', function() {
return Bot::sendMessage('Доступные команды: /start, /help');
});
// Запуск бота
$bot->start();
$bot = new PHPMaxBot('your-bot-token');
// Простая команда
$bot->command('start', function() {
return Bot::sendMessage('Привет!');
});
// Команда с параметром
$bot->command('echo', function($text) {
return Bot::sendMessage("Вы написали: $text");
});
// Команда с текстовым ответом
$bot->command('hello', 'Привет! Как дела?');
// Обработка события bot_started
$bot->on('bot_started', function() {
$update = PHPMaxBot::$currentUpdate;
$userId = $update['user']['user_id'];
$userName = $update['user']['first_name'];
return Bot::sendMessage("Добро пожаловать, $userName!");
});
// Обработка создания сообщения
$bot->on('message_created', function() {
$text = Bot::getText();
// Ваша логика
});
// Обработка нескольких событий
$bot->on('message_created|message_edited', function() {
// Обработка обоих событий
});
// Отправить сообщение в чат
Bot::sendMessageToChat($chatId, 'Текст сообщения', [
'attachments' => [$keyboard],
'format' => 'markdown'
]);
// Отправить сообщение пользователю
Bot::sendMessageToUser($userId, 'Текст сообщения');
// Отправить сообщение (автоопределение получателя)
// В групповом чате отправляет в чат, в личном диалоге — пользователю
Bot::sendMessage('Текст сообщения');
// Явно указать получателя через $extra
Bot::sendMessage('Текст', ['chat_id' => $chatId]);
Bot::sendMessage('Текст', ['user_id' => $userId]);
// Получить сообщение по ID
Bot::getMessage($messageId);
// Получить сообщения чата
Bot::getMessages($chatId, [
'count' => 10,
'from' => 0
]);
// Редактировать сообщение
Bot::editMessage($messageId, [
'text' => 'Новый текст'
]);
// Удалить сообщение
Bot::deleteMessage($messageId);
// Получить все чаты
Bot::getAllChats();
// Получить чат по ID
Bot::getChat($chatId);
// Получить чат по ссылке
Bot::getChatByLink($chatLink);
// Редактировать информацию о чате
Bot::editChatInfo($chatId, [
'title' => 'Новое название'
]);
// Удалить чат
Bot::deleteChat($chatId);
// Получить участников чата
Bot::getChatMembers($chatId);
// Добавить участников
Bot::addChatMembers($chatId, [$userId1, $userId2]);
// Удалить участника
Bot::removeChatMember($chatId, $userId);
// Получить администраторов
Bot::getChatAdmins($chatId);
// Назначить администратора
Bot::addChatAdmin($chatId, $userId);
// Снять администратора
Bot::removeChatAdmin($chatId, $userId);
// Покинуть чат
Bot::leaveChat($chatId);
// Получить закрепленное сообщение
Bot::getPinnedMessage($chatId);
// Закрепить сообщение
Bot::pinMessage($chatId, $messageId);
// Открепить сообщение
Bot::unpinMessage($chatId);
// Получить информацию о боте
Bot::getMyInfo();
// Редактировать информацию о боте
Bot::editMyInfo([
'name' => 'Новое имя',
'description' => 'Описание'
]);
// Установить команды бота
Bot::setMyCommands([
['name' => 'start', 'description' => 'Запустить бота'],
['name' => 'help', 'description' => 'Помощь']
]);
// Удалить команды
Bot::deleteMyCommands();
// Получить информацию о видео по токену
Bot::getVideo($videoToken);
// Получить список активных подписок
Bot::getSubscriptions();
// Создать webhook-подписку
Bot::createSubscription('https://example.com/webhook', [
'message_created',
'message_callback',
'bot_started'
]);
// Удалить подписку
Bot::deleteSubscription('https://example.com/webhook');
// Отправить изображение в чат (один вызов)
Bot::sendImageToChat($chatId, '/path/to/photo.jpg', 'Подпись');
// Отправить видео пользователю
Bot::sendVideoToUser($userId, '/path/to/video.mp4', 'Подпись');
// Отправить действие (печатает, отправляет файл и т.д.)
Bot::sendAction($chatId, 'typing_on');
// Ответить на callback с уведомлением
Bot::answerOnCallback($callbackId, [
'notification' => 'Готово!'
]);
// Ответить с изменением сообщения
Bot::answerOnCallback($callbackId, [
'message' => [
'text' => 'Новый текст',
'attachments' => [$newKeyboard]
]
]);
// MarkDown
$bot->setFormat('markdown');
$bot->setFormat('md');
// HTML
$bot->setFormat('html');
// Простой текст
$bot->setFormat();
$bot->setFormat(false);
$bot = new PHPMaxBot($token);
// Настройка обработчиков...
$bot->start();
use PHPMaxBot\Exceptions\ApiException;
use PHPMaxBot\Exceptions\MaxBotException;
try {
Bot::sendMessage('Привет!');
} catch (ApiException $e) {
// Ошибка API MAX
echo "API Error: " . $e->getMessage();
echo "Error Code: " . $e->getApiErrorCode();
} catch (MaxBotException $e) {
// Общая ошибка PHPMaxBot
echo "Error: " . $e->getMessage();
print_r($e->getContext());
}
// Получить полные данные обновления
$update = PHPMaxBot::$currentUpdate;
// Вспомогательные методы
$type = Bot::type(); // Тип обновления
$text = Bot::getText(); // Текст сообщения
$callbackData = Bot::getCallbackData(); // Данные callback
$contact = Bot::getContact(); // vCard (если пользователь поделился контактом)
$sender = Bot::getSender(); // Данные отправителя (id, имя, etc)
// message_created — отправитель и чат
$bot->on('message_created', function() {
$update = PHPMaxBot::$currentUpdate;
$userId = $update['message']['sender']['user_id'] ?? null;
// групповой чат:
$chatId = $update['message']['recipient']['chat_id'] ?? null;
// тип чата: 'dialog' | 'chat' | 'channel'
$chatType = $update['message']['recipient']['chat_type'] ?? null;
});
// message_callback — кто нажал кнопку и где
$bot->action('my_button', function() {
$update = PHPMaxBot::$currentUpdate;
$userId = $update['callback']['sender']['user_id'];
$callbackId = $update['callback']['callback_id'];
// сообщение с кнопкой — в $update['callback']['message'], не в $update['message']
$messageId = $update['callback']['message']['body']['mid'] ?? null;
$chatId = $update['callback']['message']['recipient']['chat_id'] ?? null;
return Bot::answerOnCallback($callbackId, ['notification' => 'OK']);
});
// bot_started — кто запустил бота
$bot->on('bot_started', function() {
$update = PHPMaxBot::$currentUpdate;
$userId = $update['user']['user_id'];
$firstName = $update['user']['first_name'];
$chatId = $update['chat_id']; // ID личного диалога
$payload = $update['payload'] ?? null; // deeplink-параметр
});
// user_added — кто добавлен и кем
$bot->on('user_added', function() {
$update = PHPMaxBot::$currentUpdate;
$userId = $update['user']['user_id']; // добавленный пользователь
$chatId = $update['chat_id'];
$inviterId = $update['inviter_id'] ?? null; // кто добавил
});
// user_removed — кто удалён и кем
$bot->on('user_removed', function() {
$update = PHPMaxBot::$currentUpdate;
$userId = $update['user']['user_id']; // удалённый пользователь
$chatId = $update['chat_id'];
$adminId = $update['admin_id'] ?? null; // кто удалил
});
// chat_title_changed — кто сменил название
$bot->on('chat_title_changed', function() {
$update = PHPMaxBot::$currentUpdate;
$userId = $update['user']['user_id'];
$chatId = $update['chat_id'];
$newTitle = $update['title'];
});
// message_removed — прямые поля, без вложенного объекта user
$bot->on('message_removed', function() {
$update = PHPMaxBot::$currentUpdate;
$userId = $update['user_id']; // не $update['user']['user_id']
$chatId = $update['chat_id'];
$messageId = $update['message_id'];
});
// bot_added — бот добавлен в чат или канал
$bot->on('bot_added', function() {
$update = PHPMaxBot::$currentUpdate;
$userId = $update['user']['user_id']; // кто добавил
$chatId = $update['chat_id'];
$isChannel = $update['is_channel'] ?? false;
});