yourtar-cli 2.0.0 → 2.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,79 @@
1
+ <?php
2
+
3
+ namespace App\Service\MessageThemeService;
4
+
5
+ use App\Entity\Chat;
6
+ use App\Entity\DialogContext;
7
+ use App\Service\MessengerService\VkService;
8
+ use Doctrine\ORM\EntityManagerInterface;
9
+ use Psr\Log\LoggerInterface;
10
+
11
+ class MessageServiceTemplate implements MessageThemeInterface
12
+ {
13
+ private ?EntityManagerInterface $em = null;
14
+
15
+ private ?LoggerInterface $logger;
16
+
17
+ private $paginationCount = 3;
18
+ private $comission = 10;
19
+
20
+ public function __construct(EntityManagerInterface $em, LoggerInterface $logger)
21
+ {
22
+ $this->em = $em;
23
+ $this->logger = $logger;
24
+ }
25
+
26
+ public function processMessage(array $message):bool
27
+ {
28
+ $isProcessed = true;
29
+
30
+ $chat = $this->em->getRepository(Chat::class)->findOneBy(array('chatId' => $message['from']), array('id' => 'desc'));
31
+ $context = $this->em->getRepository(DialogContext::class)->findOneBy(['chat' => $chat]);
32
+ if (array_key_exists('message', $message)) {
33
+ $from = $message['from'];
34
+
35
+ $arr = explode(' ', $message['message']);
36
+
37
+ //Comment: Это свитч для работы с командами и ручным вводом
38
+ switch (strtolower($arr[0])) {
39
+ case 'example':
40
+
41
+ break;
42
+ default:
43
+ if ($context instanceof DialogContext) {
44
+ //Comment: Это свитч для работы с контектом ввода (когда вводят ответ на вопрос бота)
45
+ switch ($context->getContext()['data'][0]) {
46
+ case 'example':
47
+
48
+ break;
49
+ default:
50
+ $isProcessed = false;
51
+ break;
52
+ }
53
+ }
54
+ else $isProcessed = false;
55
+ break;
56
+ }
57
+ }
58
+ else if (array_key_exists('data', $message)) {
59
+ $arr = json_decode($message['data'], true);
60
+
61
+ //Comment: Это свитч для работы с командами и ручным вводом
62
+ switch ($arr['command']) {
63
+ case 'example':
64
+ // $chat->getMessenger()->deleteMessage($message['message_id'], $chat);
65
+ // $chat->getMessenger()->sendMessage("Чем хотите управлять?", $chat, [
66
+ // [['text' => 'Адреса', 'callback_data' => json_encode(array('command' => 'branchList',)),]],
67
+ // [['text' => 'Услуги', 'callback_data' => json_encode(array('command' => 'serviceList',)),]],
68
+ // [['text' => 'Пользоваатели', 'callback_data' => json_encode(array('command' => 'users',)),]],
69
+ // ]);
70
+ break;
71
+ default:
72
+ $isProcessed = false;
73
+ break;
74
+ }
75
+ }
76
+
77
+ return $isProcessed;
78
+ }
79
+ }
@@ -0,0 +1,8 @@
1
+ <?php
2
+
3
+ namespace App\Service\MessageThemeService;
4
+
5
+ interface MessageThemeInterface
6
+ {
7
+ public function processMessage(array $message): bool;
8
+ }
@@ -0,0 +1,275 @@
1
+ <?php
2
+
3
+ namespace App\Service\MessengerService;
4
+
5
+ use App\Entity\Chat;
6
+ use CURLFile;
7
+ use Exception;
8
+
9
+ class MaxService implements MessengerInterface
10
+ {
11
+ private ?string $token = null;
12
+ private ?Chat $chat = null;
13
+
14
+ public function __construct(?Chat $chat = null)
15
+ {
16
+ $this->chat = $chat;
17
+ $this->token = $_ENV['MAX_TOKEN'];
18
+ }
19
+
20
+ public function normalizeMessage(array $message): array
21
+ {
22
+ $data = $message['update_type'] === 'message_callback' ? array(
23
+ 'callback_query' => array(
24
+ 'message' => array(
25
+ 'chat' => array('id' => $message['message']['recipient']['chat_id']),
26
+ 'message_id' => $message['message']['body']['mid'],
27
+ ),
28
+ 'data' => $message['callback']['payload'],
29
+ ),
30
+ ) : array(
31
+ 'message' => $message['message']['body']['text'] ?? null,
32
+ 'chatId' => $message['chat_id'] ?? $message['message']['recipient']['chat_id'],
33
+ 'from' => $message['chat_id'] ?? $message['message']['recipient']['chat_id'],
34
+ 'username' => array_key_exists('user', $message) ? $message['user']['last_name'] . ' ' . $message['user']['first_name'] : null,
35
+ 'userId' => $message['user']['user_id'] ?? $message['message']['recipient']['user_id'],
36
+ 'type' => 'MAX',
37
+ );
38
+ if (array_key_exists('message', $message) && array_key_exists('body', $message['message']) && array_key_exists('attachments', $message['message']['body'])) {
39
+ $phone = 'fuck';
40
+ foreach ($message['message']['body']['attachments'] as $attachment) {
41
+ if ($attachment['type'] === 'contact') {
42
+ $str = $attachment['payload']['vcf_info'];
43
+ $str = explode('cell:', $str)[1];
44
+ if (is_string($str)) {
45
+ $str = explode('\r\n', $str)[0];
46
+ }
47
+ if (is_string($str)) {
48
+ $phone = preg_replace('/[^0-9+]/', '', $str);
49
+ $phone = substr($phone, -10);
50
+ }
51
+ }
52
+ }
53
+ if ($phone /*&& strlen($phone) === 10*/) $data['phone'] = $phone;
54
+ }
55
+ if ($message['update_type'] === 'bot_started') $data['message'] = '/start';
56
+ $data['type'] = 'MAX';
57
+
58
+ return $data;
59
+ }
60
+
61
+ public function sendMessage(string $message, ?array $buttons = null, ?array $photos = null)
62
+ {
63
+ $data = array ("text" => $message, 'format' => 'html',);
64
+ if ($buttons !== null && count($buttons) > 0) {
65
+ $buttonsAttach = array();
66
+ foreach ($buttons as $key => $buttonLine) {
67
+ $buttonsAttach[] = array();
68
+ foreach ($buttonLine as $button) {
69
+ if (array_key_exists('request_contact', $button)) $buttonsAttach[$key][] = array(
70
+ "text" => $button['text'],
71
+ 'type' => 'request_contact',
72
+ );
73
+ else $buttonsAttach[$key][] = array(
74
+ "text" => $button['text'],
75
+ 'type' => 'callback',
76
+ 'payload' => $button['callback_data'],
77
+ );
78
+ }
79
+ }
80
+
81
+ $data['attachments'] = array(
82
+ array(
83
+ 'type' => 'inline_keyboard',
84
+ 'payload' => array(
85
+ 'buttons' => $buttonsAttach,
86
+ ),
87
+ )
88
+ );
89
+ }
90
+
91
+ $resp = $this->sendRequest('messages?chat_id=' . $this->chat->getChatId(), 'POST', json_encode($data));
92
+
93
+ return $resp;
94
+ }
95
+
96
+ public function sendKeyboardMessage(string $message, ?array $buttons = null)
97
+ {
98
+ return $this->sendMessage($message, $buttons);
99
+ }
100
+
101
+ public function sendVideo(string $message, ?string $video = null)
102
+ {
103
+ // $curl = curl_init();
104
+ //
105
+ // curl_setopt_array($curl, array(
106
+ // CURLOPT_URL => 'https://api.telegram.org/bot' . $this->token . '/sendVideo?',
107
+ // CURLOPT_RETURNTRANSFER => true,
108
+ // CURLOPT_ENCODING => '',
109
+ // CURLOPT_MAXREDIRS => 10,
110
+ // CURLOPT_TIMEOUT => 0,
111
+ // CURLOPT_FOLLOWLOCATION => true,
112
+ // CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
113
+ // CURLOPT_CUSTOMREQUEST => 'POST',
114
+ // CURLOPT_POSTFIELDS => array('video' => new CURLFILE($video), 'caption' => $message, 'chat_id' => $this->chatId,
115
+ // 'width' => 1920, 'height' => 1080, 'cover' => new CURLFILE('/var/www/html/public/files/1.png')),
116
+ // ));
117
+ //
118
+ // $resp = curl_exec($curl);
119
+ // curl_close($curl);
120
+ //
121
+ // return json_decode($resp, true);
122
+ }
123
+
124
+ public function getFile(array|string $id)
125
+ {
126
+ // $curl = curl_init();
127
+ // curl_setopt_array($curl, array(
128
+ // CURLOPT_URL => 'https://api.telegram.org/bot' . $this->token . '/getFile?file_id=' . $id,
129
+ // CURLOPT_RETURNTRANSFER => true,
130
+ // CURLOPT_ENCODING => '',
131
+ // CURLOPT_MAXREDIRS => 10,
132
+ // CURLOPT_TIMEOUT => 0,
133
+ // CURLOPT_FOLLOWLOCATION => true,
134
+ // CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
135
+ // CURLOPT_CUSTOMREQUEST => 'GET',
136
+ // ));
137
+ // $response = json_decode(curl_exec($curl), true);
138
+ // curl_close($curl);
139
+ //
140
+ // if (array_key_exists('result', $response)) {
141
+ // $response = $response['result'];
142
+ //
143
+ // $fileUrl = "https://api.telegram.org/file/bot" . $this->token . "/" . $response['file_path'];
144
+ // $fileContents = file_get_contents($fileUrl);
145
+ // $filename = basename($response['file_path']);
146
+ //
147
+ // file_put_contents("/var/www/html/public/downloads/$filename", $fileContents);
148
+ //
149
+ // return $filename;
150
+ // }
151
+ //
152
+ // return false;
153
+ }
154
+
155
+ public function deleteMessage(string $id)
156
+ {
157
+ $resp = $this->sendRequest('messages?message_id=' . $id, 'DELETE');
158
+ return $resp;
159
+ }
160
+
161
+ public function checkSubscribe($userId)
162
+ {
163
+ // $channelId = '@SrbRF';
164
+ // $channelId = '@yourtar';
165
+ // $curl = curl_init();
166
+ // curl_setopt_array($curl, array(
167
+ // CURLOPT_URL => 'https://api.telegram.org/bot' . $this->token . '/getChatMember?chat_id=' . $channelId . '&user_id=' . $userId,
168
+ // CURLOPT_RETURNTRANSFER => true,
169
+ // CURLOPT_ENCODING => '',
170
+ // CURLOPT_MAXREDIRS => 10,
171
+ // CURLOPT_TIMEOUT => 0,
172
+ // CURLOPT_FOLLOWLOCATION => true,
173
+ // CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
174
+ // CURLOPT_CUSTOMREQUEST => 'GET',
175
+ // ));
176
+ // $resp = json_decode(curl_exec($curl), true);
177
+ // curl_close($curl);
178
+ //
179
+ // return $resp;
180
+ }
181
+
182
+ public function sendDocument(string $message, string $document, ?array $buttons = null)
183
+ {
184
+ //get link for file upload
185
+ $resp = $this->sendRequest('uploads?type=file', 'POST');
186
+
187
+ //upload file
188
+ if (!array_key_exists('url', $resp)) return []; //fix correct error data
189
+ $curl = curl_init($resp['url']);
190
+ curl_setopt($curl, CURLOPT_POST, true);
191
+ curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
192
+ curl_setopt($curl, CURLOPT_POSTFIELDS, array('data' => new CURLfile($document)));
193
+ $resp = json_decode(curl_exec($curl), true);
194
+ $error = curl_error($curl);
195
+ curl_close($curl);
196
+ $fileToken = $resp['token'];
197
+
198
+ //send file
199
+ $data = array ("text" => $message, 'format' => 'html',);
200
+ if ($buttons !== null && count($buttons) > 0) {
201
+ $buttonsAttach = array();
202
+ foreach ($buttons as $key => $buttonLine) {
203
+ $buttonsAttach[] = array();
204
+ foreach ($buttonLine as $button) {
205
+ $buttonsAttach[$key][] = array(
206
+ "text" => $button['text'],
207
+ 'type' => 'callback',
208
+ 'payload' => $button['callback_data'],
209
+ );
210
+ }
211
+ }
212
+
213
+ $data['attachments'] = array(
214
+ array(
215
+ 'type' => 'inline_keyboard',
216
+ 'payload' => array(
217
+ 'buttons' => $buttonsAttach,
218
+ ),
219
+ )
220
+ );
221
+ }
222
+ if (!array_key_exists('attachments', $data)) $data['attachments'] = array();
223
+ $data['attachments'][] = array(
224
+ 'type' => 'file',
225
+ 'payload' => array('token' => $fileToken),
226
+ );
227
+
228
+ sleep(2);
229
+ $resp = $this->sendRequest('messages?chat_id=' . $this->chat->getChatId(), 'POST', json_encode($data));
230
+
231
+ return $resp;
232
+ }
233
+
234
+ /**
235
+ * @throws Exception
236
+ */
237
+ private function sendRequest(string $uri, string $method = 'GET', null|array|string $body = null) {
238
+ $curl = curl_init();
239
+ curl_setopt_array($curl, array(
240
+ CURLOPT_URL => 'https://platform-api.max.ru/' . $uri,
241
+ CURLOPT_RETURNTRANSFER => true,
242
+ CURLOPT_ENCODING => '',
243
+ CURLOPT_MAXREDIRS => 10,
244
+ CURLOPT_TIMEOUT => 0,
245
+ CURLOPT_FOLLOWLOCATION => true,
246
+ CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
247
+ CURLOPT_CUSTOMREQUEST => $method,
248
+ CURLOPT_HTTPHEADER => is_string($body) ? array(
249
+ 'Content-Type: application/json',
250
+ 'Authorization: ' . $this->token,
251
+ ) : array(
252
+ 'Authorization: ' . $this->token,
253
+ ),
254
+ ));
255
+ if (!is_null($body)) curl_setopt($curl, CURLOPT_POSTFIELDS, $body);
256
+
257
+ $resp = curl_exec($curl);
258
+
259
+ if (curl_errno($curl)) {
260
+ throw new Exception('Connection Error: ' . curl_error($curl));
261
+ } else {
262
+ $http_status = curl_getinfo($curl, CURLINFO_HTTP_CODE);
263
+
264
+ if ($http_status != 200) {
265
+ throw new Exception("Request failed with HTTP Code: " . $http_status);
266
+ }
267
+ }
268
+
269
+ $resp = json_decode($resp, true);
270
+
271
+ curl_close($curl);
272
+
273
+ return $resp;
274
+ }
275
+ }
@@ -0,0 +1,22 @@
1
+ <?php
2
+
3
+ namespace App\Service\MessengerService;
4
+
5
+ use App\Entity\Chat;
6
+
7
+ interface MessengerInterface
8
+ {
9
+ public function normalizeMessage(array $message): array;
10
+
11
+ public function sendMessage(string $message, ?array $buttons = null, ?array $photos = null);
12
+
13
+ public function sendKeyboardMessage(string $message, ?array $buttons = null);
14
+
15
+ public function sendVideo(string $message, string $video);
16
+
17
+ public function getFile(array|string $id);
18
+
19
+ public function deleteMessage(string $id);
20
+
21
+ public function sendDocument(string $message, string $document, ?array $buttons = null);
22
+ }
@@ -0,0 +1,195 @@
1
+ <?php
2
+
3
+ namespace App\Service\MessengerService;
4
+
5
+ use App\Entity\Chat;
6
+ use CURLFile;
7
+ use Exception;
8
+
9
+ class TelegramService implements MessengerInterface
10
+ {
11
+
12
+ private ?Chat $chat = null;
13
+ private ?string $token = null;
14
+
15
+ public function __construct(?Chat $chat = null)
16
+ {
17
+ $this->token = $_ENV['TG_TOKEN'];
18
+ $this->chat = $chat;
19
+ }
20
+
21
+ public function normalizeMessage(array $message): array
22
+ {
23
+ $result = array();
24
+
25
+ if (array_key_exists('message', $message)) {
26
+ //user and chat
27
+ if (array_key_exists('chat', $message['message']) && array_key_exists('id', $message['message']['chat']))
28
+ $result['from'] = $message['message']['chat']['id'];
29
+ if (array_key_exists('chat', $message['message']) && array_key_exists('username', $message['message']['chat']))
30
+ $result['username'] = $message['message']['chat']['username'];
31
+ if (array_key_exists('from', $message['message']) && array_key_exists('id', $message['message']['from']))
32
+ $result['userId'] = $message['message']['from']['id'];
33
+ if (array_key_exists('contact', $message['message']) && array_key_exists('phone_number', $message['message']['contact']))
34
+ $result['phone'] = $message['message']['contact']['phone_number'];
35
+
36
+ //text
37
+ if (array_key_exists('text', $message['message'])) $result['message'] = $message['message']['text'];
38
+ else $result['message'] = '';
39
+
40
+ //files
41
+ if (array_key_exists('media_group_id', $message['message'])) $result['media_group_id'] = $message['message']['media_group_id'];
42
+ if (array_key_exists('document', $message['message'])) $result['documents'] = array($message['message']['document']['file_id']);
43
+ if (array_key_exists('photo', $message['message'])) {
44
+ $result['photos'] = array();
45
+ foreach ($message['message']['photo'] as $item) {
46
+ $result['photos'][] = $item['file_id'];
47
+ }
48
+ }
49
+ } elseif (array_key_exists('callback_query', $message)) {
50
+ if (array_key_exists('message', $message['callback_query']) && array_key_exists('chat', $message['callback_query']['message']) &&
51
+ array_key_exists('id', $message['callback_query']['message']['chat'])) $result['from'] = $message['callback_query']['message']['chat']['id'];
52
+ if (array_key_exists('data', $message['callback_query'])) $result['data'] = $message['callback_query']['data'];
53
+ if (array_key_exists('message', $message['callback_query']) && array_key_exists('message_id', $message['callback_query']['message']))
54
+ $result['message_id'] = $message['callback_query']['message']['message_id'];
55
+
56
+ }
57
+ $result['type'] = 'TG';
58
+
59
+ return $result;
60
+ }
61
+
62
+ public function sendMessage(string $message, ?array $buttons = null, ?array $photos = null)
63
+ {
64
+ $keyboard = "&parse_mode=HTML" . (is_array($buttons) ? '&reply_markup=' . urlencode(json_encode([
65
+ "inline_keyboard" => $buttons,
66
+ "remove_keyboard" => true,
67
+ ])) : '');
68
+
69
+ $method = is_array($photos) ? 'POST' : 'GET';
70
+ $body = null; $path = null;
71
+
72
+ if ($method === 'POST') {
73
+ if (count($photos) === 1) {
74
+ $photo = end($photos);
75
+ if (!str_contains($photo, '/var/www/html/public/downloads/')) $photo = '/var/www/html/public/downloads/' . $photo;
76
+ $body = array('photo' => new CURLFILE($photo), 'caption' => $message, 'chat_id' => $this->chat->getChatId());
77
+ $path = 'sendPhoto?' . $keyboard;
78
+ } else {
79
+ $body = array('chat_id' => $this->chat->getChatId());
80
+ $media = array();
81
+ foreach ($photos as $key => $photo) {
82
+ if (!str_contains($photo, '/var/www/html/public/downloads/')) $photo = '/var/www/html/public/downloads/' . $photo;
83
+ $body[$photo] = new CURLFILE($photo);
84
+ $media[$key] = array(
85
+ 'type' => 'photo',
86
+ 'media' => 'attach://' . $photo,
87
+ );
88
+ }
89
+ $body['media'] = json_encode($media);
90
+
91
+ $resp = $this->sendRequest('sendMediaGroup', 'POST', $body);
92
+ }
93
+ } else $path = 'sendMessage?chat_id=' . $this->chat->getChatId() . $keyboard . '&text=' . urlencode($message);
94
+
95
+ $resp = $this->sendRequest($path, $method, $body);
96
+
97
+ return $resp;
98
+ }
99
+
100
+ public function sendKeyboardMessage(string $message, ?array $buttons = null)
101
+ {
102
+ $keyboard = "&parse_mode=HTML" . (is_array($buttons) ? '&reply_markup=' . urlencode(json_encode([
103
+ "keyboard" => $buttons,
104
+ "resize_keyboard" => true,
105
+ "one_time_keyboard" => true,
106
+ "hide_keyboard" => true,
107
+ ])) : '');
108
+
109
+ $resp = $this->sendRequest('sendMessage?chat_id=' . $this->chat->getChatId() . $keyboard . '&text=' . urlencode($message));
110
+
111
+ return $resp;
112
+ }
113
+
114
+ public function sendVideo(string $message, ?string $video = null)
115
+ {
116
+ $body = array('video' => new CURLFILE($video), 'caption' => $message, 'chat_id' => $this->chat->getChatId(),
117
+ 'width' => 1920, 'height' => 1080, 'cover' => new CURLFILE('/var/www/html/public/files/1.png'));
118
+ $resp = $this->sendRequest('sendVideo', 'POST', $body);
119
+
120
+ return $resp;
121
+ }
122
+
123
+ public function getFile(array|string $id): bool|string
124
+ {
125
+ $resp = $this->sendRequest('getFile?file_id=' . $id);
126
+
127
+ if (array_key_exists('result', $resp)) {
128
+ $resp = $resp['result'];
129
+
130
+ $fileUrl = "https://api.telegram.org/file/bot" . $this->token . "/" . $resp['file_path'];
131
+ $fileContents = file_get_contents($fileUrl);
132
+ $filename = basename($resp['file_path']);
133
+
134
+ file_put_contents("/var/www/html/public/downloads/$filename", $fileContents);
135
+
136
+ return $filename;
137
+ }
138
+
139
+ return false;
140
+ }
141
+
142
+ public function deleteMessage(string $id)
143
+ {
144
+ $resp = $this->sendRequest('deleteMessage?chat_id=' . $this->chat->getChatId() . '&message_id=' . $id);
145
+ }
146
+
147
+ public function checkSubscribe($userId)
148
+ {
149
+ $channelId = '@igromania';
150
+ $resp = $this->sendRequest('getChatMember?chat_id=' . $channelId . '&user_id=' . $userId);
151
+ return $resp;
152
+ }
153
+
154
+ public function sendDocument(string $message, string $document, ?array $buttons = null)
155
+ {
156
+ $body = array('document' => new CURLFILE($document), 'caption' => $message, 'chat_id' => $this->chat->getChatId());
157
+ $resp = $this->sendRequest('sendDocument', 'POST', $body);
158
+ }
159
+
160
+ /**
161
+ * @throws Exception
162
+ */
163
+ private function sendRequest(string $uri, string $method = 'GET', ?array $body = null) {
164
+ $curl = curl_init();
165
+ curl_setopt_array($curl, array(
166
+ CURLOPT_URL => 'https://api.telegram.org/bot' . $this->token . '/' . $uri,
167
+ CURLOPT_RETURNTRANSFER => true,
168
+ CURLOPT_ENCODING => '',
169
+ CURLOPT_MAXREDIRS => 10,
170
+ CURLOPT_TIMEOUT => 0,
171
+ CURLOPT_FOLLOWLOCATION => true,
172
+ CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
173
+ CURLOPT_CUSTOMREQUEST => $method,
174
+ ));
175
+ if (!is_null($body)) curl_setopt($curl, CURLOPT_POSTFIELDS, $body);
176
+
177
+ $resp = curl_exec($curl);
178
+
179
+ if (curl_errno($curl)) {
180
+ throw new Exception('Connection Error: ' . curl_error($curl));
181
+ } else {
182
+ $http_status = curl_getinfo($curl, CURLINFO_HTTP_CODE);
183
+
184
+ if ($http_status != 200) {
185
+ throw new Exception("Request failed with HTTP Code: " . $http_status);
186
+ }
187
+ }
188
+
189
+ $resp = json_decode($resp, true);
190
+
191
+ curl_close($curl);
192
+
193
+ return $resp;
194
+ }
195
+ }