-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathsample.php
More file actions
187 lines (161 loc) · 6.27 KB
/
sample.php
File metadata and controls
187 lines (161 loc) · 6.27 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
<?php
/**
* Sample bot using PHPMaxBot
*
* This example demonstrates the basic usage of PHPMaxBot library
*/
require_once __DIR__ . '/vendor/autoload.php';
use PHPMaxBot\Helpers\Keyboard;
// Get bot token from environment or set it directly
$token = getenv('BOT_TOKEN') ?: 'your-bot-token-here';
// Create bot instance
$bot = new PHPMaxBot($token);
// Set bot commands (optional)
try {
Bot::setMyCommands([
['name' => 'start', 'description' => 'Start the bot'],
['name' => 'help', 'description' => 'Show help message'],
['name' => 'keyboard', 'description' => 'Show keyboard example'],
['name' => 'echo', 'description' => 'Echo your message']
]);
} catch (Exception $e) {
echo "Warning: Could not set commands: " . $e->getMessage() . "\n";
}
// Handle /start command
$bot->command('start', function($param) {
$text = "Привет! Я бот на MAX мессенджере.\n\n";
$text .= "Доступные команды:\n";
$text .= "/help - Помощь\n";
$text .= "/keyboard - Показать клавиатуру\n";
$text .= "/echo текст - Повторить текст\n";
return Bot::sendMessage($text);
});
// Handle /help command
$bot->command('help', function() {
return Bot::sendMessage("Это бот-пример на PHPMaxBot. Используйте /start для начала работы.");
});
// Handle /echo command with parameter
$bot->command('echo', function($text) {
if (empty($text)) {
return Bot::sendMessage("Использование: /echo <текст>");
}
return Bot::sendMessage("Вы написали: " . $text);
});
// Handle /keyboard command - show inline keyboard
$bot->command('keyboard', function() {
$keyboard = Keyboard::inlineKeyboard([
[
Keyboard::callback('Кнопка 1', 'button_1'),
Keyboard::callback('Кнопка 2', 'button_2', ['intent' => 'positive'])
],
[
Keyboard::callback('Удалить сообщение', 'delete_message', ['intent' => 'negative'])
],
[
Keyboard::link('Открыть MAX', 'https://max.ru/')
],
[
Keyboard::requestContact('Отправить контакт')
],
[
Keyboard::requestGeoLocation('Отправить геолокацию')
]
]);
return Bot::sendMessage('Выберите действие:', [
'attachments' => [$keyboard]
]);
});
// Handle callback button: button_1
$bot->action('button_1', function() {
$update = PHPMaxBot::$currentUpdate;
$callbackId = $update['callback']['callback_id'];
return Bot::answerOnCallback($callbackId, [
'notification' => 'Вы нажали на кнопку 1!'
]);
});
// Handle callback button: button_2
$bot->action('button_2', function() {
$update = PHPMaxBot::$currentUpdate;
$callbackId = $update['callback']['callback_id'];
return Bot::answerOnCallback($callbackId, [
'message' => [
'text' => 'Вы нажали на кнопку 2! Сообщение изменено.',
'attachments' => null
]
]);
});
// Handle callback button: delete_message
$bot->action('delete_message', function() {
$update = PHPMaxBot::$currentUpdate;
$callbackId = $update['callback']['callback_id'];
// message_callback: сообщение с кнопкой лежит в $update['callback']['message'], не в $update['message']
$messageId = $update['callback']['message']['body']['mid'] ?? null;
if ($messageId) {
try {
Bot::deleteMessage($messageId);
return Bot::answerOnCallback($callbackId, [
'notification' => 'Сообщение удалено'
]);
} catch (Exception $e) {
return Bot::answerOnCallback($callbackId, [
'notification' => 'Не удалось удалить сообщение'
]);
}
}
});
// Handle pattern matching for callbacks (regex)
$bot->action('color:(.+)', function($matches) {
$update = PHPMaxBot::$currentUpdate;
$callbackId = $update['callback']['callback_id'];
$color = $matches[1];
return Bot::answerOnCallback($callbackId, [
'message' => [
'text' => "Вы выбрали цвет: $color",
'attachments' => null
]
]);
});
// Handle bot_started event (when user starts bot for the first time)
// bot_started: userId → $update['user']['user_id']
// chatId → $update['chat_id'] (ID личного диалога)
// payload → $update['payload'] (deeplink-параметр, если есть)
$bot->on('bot_started', function() {
$update = PHPMaxBot::$currentUpdate;
$userId = $update['user']['user_id'];
$userName = $update['user']['first_name'] ?? 'пользователь';
$chatId = $update['chat_id'];
$payload = $update['payload'] ?? null;
$text = "Привет, $userName! Спасибо, что запустили бота.";
if ($payload) {
$text .= "\nПараметр запуска: $payload";
}
return Bot::sendMessage($text);
});
// Handle location attachment (user pressed «Отправить геолокацию»)
$bot->onAttachment('location', function($attachment) {
$lat = $attachment['latitude'];
$lon = $attachment['longitude'];
return Bot::sendMessage("Получена геолокация: $lat, $lon");
});
// Handle contact attachment (user pressed «Отправить контакт»)
$bot->onAttachment('contact', function($attachment) {
$firstName = $attachment['payload']['max_info']['first_name'] ?? 'Unknown';
$lastName = $attachment['payload']['max_info']['last_name'] ?? '';
$name = trim("$firstName $lastName");
return Bot::sendMessage("Получен контакт: $name");
});
// Handle regular text messages (non-command)
$bot->on('message_created', function() {
// onAttachment handlers above take priority for messages with attachments.
// This handler receives only plain text messages that are not commands.
});
// Start the bot
// In CLI mode: long polling
// In web mode: webhook
$bot->start([
'message_created',
'message_callback',
'bot_started',
'message_edited',
'message_removed'
]);