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.
@@ -1,256 +0,0 @@
1
- <?php
2
-
3
- namespace App\Service;
4
-
5
- use App\Entity\Chat;
6
- use App\Entity\Branch;
7
- use App\Entity\Service;
8
- use App\Entity\DialogContext;
9
- use App\Entity\Order;
10
- use App\Entity\OrderItem;
11
- use App\Entity\Payment;
12
- use App\Repository\ChatRepository;
13
- use App\Repository\DialogContextRepository;
14
- use Doctrine\ORM\EntityManagerInterface;
15
- use Psr\Log\LoggerInterface;
16
- use setasign\Fpdi\Fpdi;
17
- use Symfony\Component\Mime\MimeTypes;
18
-
19
- class MessageProcessService
20
- {
21
- private ?ChatRepository $chatRepo = null;
22
- private ?TelegramService $telegram = null;
23
- private ?EntityManagerInterface $em = null;
24
-
25
- private ?DialogContextRepository $dialogRepo = null;
26
- private ?RobokassaService $robokassa;
27
- private ?LoggerInterface $logger;
28
-
29
- private $paginationCount = 3;
30
- private $comission = 10;
31
-
32
- public function __construct(EntityManagerInterface $em, ChatRepository $chatRepo, DialogContextRepository $dialogRepo, LoggerInterface $logger)
33
- {
34
- $this->chatRepo = $chatRepo;
35
- $this->em = $em;
36
-
37
- $this->dialogRepo = $dialogRepo;
38
- $this->logger = $logger;
39
- $this->robokassa = new RobokassaService();
40
- }
41
-
42
- public function processMessage(array $message, TelegramService $messenger)
43
- {
44
- $this->logger->error('msg '. json_encode($message));
45
- if (array_key_exists('message', $message)) {
46
- $from = $message['from'];
47
- $chat = $this->chatRepo->findOneBy(array('chatId' => $from), array('id' => 'desc'));
48
- $isAuth = $chat instanceof Chat && !is_null($chat->getRole());
49
-
50
- $arr = explode(' ', $message['message']);
51
-
52
- //Comment: Это свитч для работы с командами и ручным вводом
53
- switch (strtolower($arr[0])) {
54
- case '/start':
55
- $isInit = false;
56
- if (!$chat instanceof Chat) {
57
- $chat = new Chat();
58
- if (array_key_exists('username', $message)) $chat->setUsername($message['username']);
59
- if (array_key_exists('userId', $message)) $chat->setUserId($message['userId']);
60
- $chat->setChatId($from);
61
-
62
- $this->chatRepo->add($chat, true);
63
- $isInit = true;
64
- }
65
- $buttons = [];
66
-
67
- $responseText = "";
68
-
69
- if ($isInit) $responseText = "Добрый день! Вы попали в чат-бота библиотеки ТУСУР!\r\n\r\n" .
70
- "В этом боте Вы можете заказать печать с другими услуагами по ксерокопии и не только с доставкой в корпус или общежитие.\r\n\r\n" .
71
- "Также для Вас данный бот предлагает возможность просмотра задолжности летиратуры перед Библиотекой ТУСУР, а также заказа литературы с доставкой в корпус или общежитие.\r\n\r\n" .
72
- "Не стойте в очереди! Мы все доставим в нужный день! Спасибо, что Вы с нами!";
73
-
74
- $this->chatRepo->add($chat, true);
75
-
76
- if (strlen($responseText) > 0) $resp = $messenger->sendMessage($responseText, $from);
77
-
78
- if (is_null($chat->getPhone())) {
79
- $resp = $messenger->sendKeyboardMessage("Если Вы сотрудник, поделитесь, пожалуйста, номером телефона для авторизации", $from, [
80
- [['text' => 'Дать свой телефончик', 'request_contact' => true]]
81
- ]);
82
- $this->logger->error('resp', $resp);
83
- }
84
- break;
85
- case '/example':
86
- $context = new DialogContext();
87
- $context->setChat($chat);
88
- $context->setContext(['data' => ['files'],]);
89
- $this->dialogRepo->add($context, true);
90
-
91
- $buttons = [];
92
- $responseText = "В данном разделе Вы можете заказать и оплатить услуги печати из Библиотеки ТУСУР с доставкой в корпус или общежитие\r\n\r\n" .
93
- "Прикрепите, пожалуйста, файлы для печати";
94
-
95
- $messenger->sendMessage($responseText, $from, $buttons);
96
- break;
97
- case '/help':
98
- case '?':
99
- $buttons = [];
100
- if ($isAuth && $chat->getRole() === Chat::ROLE_ADMIN) {
101
- $responseText = "Приветствую! Я Вас узнал) Вы из администрации Библиотеки ТУСУР\r\n" .
102
- "Что желаете сделать?\r\n\r\n" .
103
- "P.S.: бот с любовью и заботой разработан командой @yourtar";
104
- $buttons[] = [['text' => 'Админ. панель', 'callback_data' => json_encode(array('command' => 'adminMenu', )),]];
105
- $buttons[] = [['text' => 'Статистика', 'callback_data' => json_encode(array('command' => 'stats', )),]];
106
- } else {
107
- $responseText = "Добро пожаловать в чат-бота Библиотеки ТУСУР!\r\n\r\n" .
108
- "В этом боте Вы можете заказать печать с другими услуагами по ксерокопии и не только с доставкой в корпус или общежитие.\r\n\r\n" .
109
- "Также для Вас данный бот предлагает возможность просмотра задолжности летиратуры перед Библиотекой ТУСУР, а также заказа литературы с доставкой в корпус или общежитие.\r\n\r\n" .
110
- "Не стойте в очереди! Мы все доставим в нужный день! Спасибо, что Вы с нами!\r\n\r\n" .
111
- "P.S.: бот с любовью и заботой разработан командой @yourtar , большая часть которой также обучалась, а основатель и преподавал в ТУСУР!";
112
- }
113
-
114
- $messenger->sendMessage($responseText, $from, $buttons);
115
- break;
116
- default:
117
- $context = $this->dialogRepo->findOneBy(['chat' => $chat]);
118
- $noDone = true;
119
-
120
- if ($context instanceof DialogContext) {
121
- //Comment: Это свитч для работы с контектом ввода (когда вводят ответ на вопрос бота)
122
- switch ($context->getContext()['data'][0]) {
123
- case 'files':
124
- if (array_key_exists('documents', $message) && count($message['documents']) > 0 ) {
125
- $noDone = false;
126
- $this->dialogRepo->remove($context, true);
127
-
128
- $file = $messenger->getFile($message['documents'][0]);
129
-
130
- $messenger->sendMessage("No order", $from);
131
- break;
132
- }
133
- break;
134
- case 'name':
135
- if (strlen($message['message']) > 2) {
136
- $noDone = false;
137
- $this->dialogRepo->remove($context, true);
138
-
139
- $class = $context->getContext()['class'];
140
- $object = $this->em->getRepository($class)->find($context->getContext()['id']);
141
- if ($object instanceof $class) {
142
- $object->setName($message['message']);
143
- $this->em->flush();
144
-
145
- $responseText = "Данные сохранены.";
146
- $buttons = [
147
- [['text' => 'Показать список', 'callback_data' => json_encode(array('command' => strtolower(explode('\\', get_class($object))[count(explode('\\', get_class($object))) - 1]) . 'List', )),]],
148
- [['text' => 'Показать объект', 'callback_data' => json_encode(array('command' => strtolower(explode('\\', get_class($object))[count(explode('\\', get_class($object))) - 1]), 'id' => $object->getId())),]],
149
- ];
150
-
151
- $resp = $messenger->sendMessage($responseText, $from, $buttons);
152
- }
153
- }
154
- break;
155
- }
156
- }
157
- // else if (array_key_exists('photo', $message['message']) && count($message['message']['photo']) > 1 && array_key_exists('media_group_id', $message)) {
158
- // $ms = $this->em->getRepository(MessageSending::class)->findOneBy(array('photoMediaGroupId' => $message['media_group_id']));
159
-
160
- // if ($ms instanceof MessageSending) {
161
- // $file = $messenger->getFile(end($message['message']['photo'])['file_id']);
162
-
163
- // $files = $ms->getImage();
164
- // $files[] = $file;
165
- // $ms->setImage($files);
166
- // $this->em->flush();
167
- // }
168
- // }
169
- if ($noDone && array_key_exists('documents', $message) && count($message['documents']) > 0 && array_key_exists('media_group_id', $message)) {
170
- $file = $messenger->getFile($message['documents'][0]);
171
- }
172
- break;
173
- }
174
- } else if (array_key_exists('data', $message)) {
175
- $from = $message['from'];
176
- $chat = $this->chatRepo->findOneBy(array('chatId' => $from), array('id' => 'desc'));
177
- $arr = json_decode($message['data'], true);
178
- $isAuth = $chat instanceof Chat && !is_null($chat->getRole());
179
-
180
- //Comment: Это свитч для работы с командами и ручным вводом
181
- switch ($arr['command']) {
182
- case 'adminMenu':
183
- $messenger->deleteMessage($message['message_id'], $from);
184
- $messenger->sendMessage("Чем хотите управлять?", $from, [
185
- [['text' => 'Адреса', 'callback_data' => json_encode(array('command' => 'branchList', )),]],
186
- [['text' => 'Услуги', 'callback_data' => json_encode(array('command' => 'serviceList', )),]],
187
- [['text' => 'Пользоваатели', 'callback_data' => json_encode(array('command' => 'users', )),]],
188
- ]);
189
- break;
190
- default:
191
- break;
192
- }
193
- }
194
-
195
- if (array_key_exists('phone', $message)) {
196
- $from = $message['from'];
197
- $chat = $this->chatRepo->findOneBy(array('chatId' => $from), array('id' => 'desc'));
198
- $chat->setPhone($message['phone']);
199
- if (is_null($chat->getRole())) {
200
- $phone = preg_replace('/[^0-9+]/', '', $chat->getPhone());
201
- $phone = substr($phone, -10);
202
-
203
- $messenger->sendMessage("Спасибо, что поделились номером!", $from);
204
-
205
- $admins = $this->em->getRepository(Chat::class)->findByRole(Chat::ROLE_ADMIN);
206
- foreach($admins as $admin) {
207
- $messenger->sendMessage("Авторизован пользователь с номером +1" . $phone . "\r\nАвторизовать пользователя?", $admin->getChatId(), [
208
- [['text' => "Посмотреть пользователя",
209
- 'callback_data' => json_encode(array('command' => 'user', 'id' => $chat->getId())),]]
210
- ]);
211
- }
212
- } else $messenger->sendMessage("Спасибо, что поделились номером! Вы уже администратор, поэтому для Вас ничего не изменилось!", $from);
213
-
214
- $this->chatRepo->add($chat, true);
215
- }
216
- }
217
-
218
- public function normalizeData(array $message) {
219
- $result = array();
220
-
221
- //TG
222
- if (array_key_exists('message', $message)) {
223
- //user and chat
224
- if (array_key_exists('chat', $message['message']) && array_key_exists('id', $message['message']['chat']))
225
- $result['from'] = $message['message']['chat']['id'];
226
- if (array_key_exists('chat', $message['message']) && array_key_exists('username', $message['message']['chat']))
227
- $result['username'] = $message['message']['chat']['username'];
228
- if (array_key_exists('from', $message['message']) && array_key_exists('id', $message['message']['from']))
229
- $result['userId'] = $message['message']['from']['id'];
230
- if (array_key_exists('contact', $message['message']) && array_key_exists('phone_number', $message['message']['contact']))
231
- $result['phone'] = $message['message']['contact']['phone_number'];
232
-
233
- //text
234
- if (array_key_exists('text', $message['message'])) $result['message'] = $message['message']['text'];
235
- else $result['message'] = '';
236
-
237
- //files
238
- if (array_key_exists('media_group_id', $message['message'])) $result['media_group_id'] = $message['message']['media_group_id'];
239
- if (array_key_exists('document', $message['message'])) $result['documents'] = array($message['message']['document']['file_id']);
240
- if (array_key_exists('photo', $message['message'])) {
241
- $result['photos'] = array();
242
- foreach ($message['message']['photo'] as $item) {
243
- $result['photos'][] = $item['file_id'];
244
- }
245
- }
246
- } elseif (array_key_exists('callback_query', $message)) {
247
- if (array_key_exists('message', $message['callback_query']) && array_key_exists('chat', $message['callback_query']['message']) &&
248
- array_key_exists('id', $message['callback_query']['message']['chat'])) $result['from'] = $message['callback_query']['message']['chat']['id'];
249
- if (array_key_exists('data', $message['callback_query'])) $result['data'] = $message['callback_query']['data'];
250
- if (array_key_exists('message', $message['callback_query']) && array_key_exists('message_id', $message['callback_query']['message']))
251
- $result['message_id'] = $message['callback_query']['message']['message_id'];
252
- }
253
-
254
- return $result;
255
- }
256
- }
@@ -1,227 +0,0 @@
1
- <?php
2
-
3
- namespace App\Service;
4
-
5
- use CURLFile;
6
-
7
- class TelegramService
8
- {
9
- private ?string $botToken = null;
10
-
11
- public function __construct()
12
- {
13
- $this->botToken = $_ENV['BOT_TOKEN'];
14
- }
15
-
16
- public function sendMessage(string $message, string $chatId = '-4778150749', ?array $buttons = null, ?array $photos = null)
17
- {
18
- $keyboard = "&parse_mode=HTML" . (is_array($buttons) ? '&reply_markup=' . urlencode(json_encode([
19
- "inline_keyboard" => $buttons,
20
- "remove_keyboard" => true,
21
- ])) : '');
22
-
23
- $curl = curl_init();
24
-
25
- $method = is_array($photos) ? 'POST' : 'GET';
26
-
27
- if ($method === 'POST') {
28
- if (count($photos) === 1) {
29
- $photo = end($photos);
30
- if (!str_contains($photo, '/var/www/html/public/downloads/')) $photo = '/var/www/html/public/downloads/' . $photo;
31
- curl_setopt_array($curl, array(
32
- CURLOPT_URL => 'https://api.telegram.org/bot' . $this->botToken . '/sendPhoto?' . $keyboard,
33
- CURLOPT_RETURNTRANSFER => true,
34
- CURLOPT_ENCODING => '',
35
- CURLOPT_MAXREDIRS => 10,
36
- CURLOPT_TIMEOUT => 0,
37
- CURLOPT_FOLLOWLOCATION => true,
38
- CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
39
- CURLOPT_CUSTOMREQUEST => 'POST',
40
- CURLOPT_POSTFIELDS => array('photo' => new CURLFILE($photo), 'caption' => $message, 'chat_id' => $chatId),
41
- ));
42
- } else {
43
- $body = array('chat_id' => $chatId);
44
- $media = array();
45
- foreach ($photos as $key => $photo) {
46
- if (!str_contains($photo, '/var/www/html/public/downloads/')) $photo = '/var/www/html/public/downloads/' . $photo;
47
- $body[$photo] = new CURLFILE($photo);
48
- $media[$key] = array(
49
- 'type' => 'photo',
50
- 'media' => 'attach://' . $photo,
51
- );
52
- }
53
- $body['media'] = json_encode($media);
54
-
55
- $curl1 = curl_init();
56
- curl_setopt_array($curl1, array(
57
- CURLOPT_URL => 'https://api.telegram.org/bot' . $this->botToken . '/sendMediaGroup',
58
- CURLOPT_RETURNTRANSFER => true,
59
- CURLOPT_ENCODING => '',
60
- CURLOPT_MAXREDIRS => 10,
61
- CURLOPT_TIMEOUT => 0,
62
- CURLOPT_FOLLOWLOCATION => true,
63
- CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
64
- CURLOPT_CUSTOMREQUEST => 'POST',
65
- CURLOPT_POSTFIELDS => $body,
66
- ));
67
- curl_exec($curl1);
68
- curl_close($curl1);
69
- }
70
- } else curl_setopt_array($curl, array(
71
- CURLOPT_URL => 'https://api.telegram.org/bot' . $this->botToken . '/sendMessage?chat_id=' . $chatId . $keyboard . '&text=' . urlencode($message),
72
- CURLOPT_RETURNTRANSFER => true,
73
- CURLOPT_ENCODING => '',
74
- CURLOPT_MAXREDIRS => 10,
75
- CURLOPT_TIMEOUT => 0,
76
- CURLOPT_FOLLOWLOCATION => true,
77
- CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
78
- CURLOPT_CUSTOMREQUEST => 'GET',
79
- ));
80
-
81
- $resp = curl_exec($curl);
82
- curl_close($curl);
83
-
84
- return json_decode($resp, true);
85
- }
86
-
87
- public function sendKeyboardMessage(string $message, string $chatId = '-4778150749', ?array $buttons = null)
88
- {
89
- $keyboard = "&parse_mode=HTML" . (is_array($buttons) ? '&reply_markup=' . urlencode(json_encode([
90
- "keyboard" => $buttons,
91
- "resize_keyboard" => true,
92
- "one_time_keyboard" => true,
93
- "hide_keyboard" => true,
94
- ])) : '');
95
-
96
- $curl = curl_init();
97
-
98
- curl_setopt_array($curl, array(
99
- CURLOPT_URL => 'https://api.telegram.org/bot' . $this->botToken . '/sendMessage?chat_id=' . $chatId . $keyboard . '&text=' . urlencode($message),
100
- CURLOPT_RETURNTRANSFER => true,
101
- CURLOPT_ENCODING => '',
102
- CURLOPT_MAXREDIRS => 10,
103
- CURLOPT_TIMEOUT => 0,
104
- CURLOPT_FOLLOWLOCATION => true,
105
- CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
106
- CURLOPT_CUSTOMREQUEST => 'GET',
107
- ));
108
-
109
- $resp = curl_exec($curl);
110
- curl_close($curl);
111
-
112
- return json_decode($resp, true);
113
- }
114
-
115
- public function sendVideo(string $message, string $chatId = '-4778150749', ?string $video = null)
116
- {
117
- $curl = curl_init();
118
-
119
- curl_setopt_array($curl, array(
120
- CURLOPT_URL => 'https://api.telegram.org/bot' . $this->botToken . '/sendVideo?',
121
- CURLOPT_RETURNTRANSFER => true,
122
- CURLOPT_ENCODING => '',
123
- CURLOPT_MAXREDIRS => 10,
124
- CURLOPT_TIMEOUT => 0,
125
- CURLOPT_FOLLOWLOCATION => true,
126
- CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
127
- CURLOPT_CUSTOMREQUEST => 'POST',
128
- CURLOPT_POSTFIELDS => array('video' => new CURLFILE($video), 'caption' => $message, 'chat_id' => $chatId,
129
- 'width' => 1920, 'height' => 1080, 'cover' => new CURLFILE('/var/www/html/public/files/1.png')),
130
- ));
131
-
132
- $resp = curl_exec($curl);
133
- curl_close($curl);
134
-
135
- return json_decode($resp, true);
136
- }
137
-
138
- public function getFile(string $id): bool|string
139
- {
140
- $curl = curl_init();
141
- curl_setopt_array($curl, array(
142
- CURLOPT_URL => 'https://api.telegram.org/bot' . $this->botToken . '/getFile?file_id=' . $id,
143
- CURLOPT_RETURNTRANSFER => true,
144
- CURLOPT_ENCODING => '',
145
- CURLOPT_MAXREDIRS => 10,
146
- CURLOPT_TIMEOUT => 0,
147
- CURLOPT_FOLLOWLOCATION => true,
148
- CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
149
- CURLOPT_CUSTOMREQUEST => 'GET',
150
- ));
151
- $response = json_decode(curl_exec($curl), true);
152
- curl_close($curl);
153
-
154
- if (array_key_exists('result', $response)) {
155
- $response = $response['result'];
156
-
157
- $fileUrl = "https://api.telegram.org/file/bot" . $this->botToken . "/" . $response['file_path'];
158
- $fileContents = file_get_contents($fileUrl);
159
- $filename = basename($response['file_path']);
160
-
161
- file_put_contents("/var/www/html/public/downloads/$filename", $fileContents);
162
-
163
- return $filename;
164
- }
165
-
166
- return false;
167
- }
168
-
169
- public function deleteMessage(string $id, $chatId)
170
- {
171
- $curl = curl_init();
172
- curl_setopt_array($curl, array(
173
- CURLOPT_URL => 'https://api.telegram.org/bot' . $this->botToken . '/deleteMessage?chat_id=' . $chatId . '&message_id=' . $id,
174
- CURLOPT_RETURNTRANSFER => true,
175
- CURLOPT_ENCODING => '',
176
- CURLOPT_MAXREDIRS => 10,
177
- CURLOPT_TIMEOUT => 0,
178
- CURLOPT_FOLLOWLOCATION => true,
179
- CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
180
- CURLOPT_CUSTOMREQUEST => 'GET',
181
- ));
182
- json_decode(curl_exec($curl), true);
183
- curl_close($curl);
184
- }
185
-
186
- public function checkSubscribe($userId)
187
- {
188
- $channelId = '@igromania';
189
- $curl = curl_init();
190
- curl_setopt_array($curl, array(
191
- CURLOPT_URL => 'https://api.telegram.org/bot' . $this->botToken . '/getChatMember?chat_id=' . $channelId . '&user_id=' . $userId,
192
- CURLOPT_RETURNTRANSFER => true,
193
- CURLOPT_ENCODING => '',
194
- CURLOPT_MAXREDIRS => 10,
195
- CURLOPT_TIMEOUT => 0,
196
- CURLOPT_FOLLOWLOCATION => true,
197
- CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
198
- CURLOPT_CUSTOMREQUEST => 'GET',
199
- ));
200
- $resp = json_decode(curl_exec($curl), true);
201
- curl_close($curl);
202
-
203
- return $resp;
204
- }
205
-
206
- public function sendDocument(string $message, string $document, string $chatId = '105616037', ?array $buttons = null)
207
- {
208
- $keyboard = is_array($buttons) ? urlencode(json_encode([
209
- "inline_keyboard" => $buttons
210
- ])) : '';
211
-
212
- $curl = curl_init();
213
- curl_setopt_array($curl, array(
214
- CURLOPT_URL => 'https://api.telegram.org/bot' . $this->botToken . '/sendDocument',
215
- CURLOPT_RETURNTRANSFER => true,
216
- CURLOPT_ENCODING => '',
217
- CURLOPT_MAXREDIRS => 10,
218
- CURLOPT_TIMEOUT => 0,
219
- CURLOPT_FOLLOWLOCATION => true,
220
- CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
221
- CURLOPT_CUSTOMREQUEST => 'POST',
222
- CURLOPT_POSTFIELDS => array('document' => new CURLFILE($document), 'caption' => $message, 'chat_id' => $chatId),
223
- ));
224
- $response = curl_exec($curl);
225
- curl_close($curl);
226
- }
227
- }