· 5 years ago · Dec 13, 2020, 10:32 AM
1<?php
2
3namespace DigitalStar\vk_api;
4
5use CURLFile;
6use Exception;
7
8require_once('config_library.php');
9
10/**
11 * Class vk_api
12 * @package DigitalStar\vk_api
13 */
14class vk_api {
15
16 /**
17 * @var string
18 */
19 protected $version = '';
20 /**
21 * @var array|mixed
22 */
23 protected $data = [];
24 /**
25 * @var string
26 */
27 protected $auth_type = '';
28 /**
29 * @var string
30 */
31 private $token = '';
32 /**
33 * @var int
34 */
35 protected $debug_mode = 0;
36 /**
37 * @var Auth|null
38 */
39 private $auth = null;
40 /**
41 * @var array
42 */
43 private $request_ignore_error = REQUEST_IGNORE_ERROR;
44 /**
45 * @var int
46 */
47 protected $try_count_resend_file = COUNT_TRY_SEND_FILE;
48
49 /**
50 * vk_api constructor.
51 * @param $token
52 * @param $version
53 * @param null $also_version
54 * @throws VkApiException
55 */
56 public function __construct($token, $version, $also_version = null) {
57 if ($token instanceof auth) {
58 $this->auth = $token;
59 $this->version = $version;
60 $this->token = $this->auth->getAccessToken();
61 } else if (isset($also_version)) {
62 $this->auth = new Auth($token, $version);
63 $this->token = $this->auth->getAccessToken();
64 $this->version = $also_version;
65 } else {
66 $this->token = $token;
67 $this->version = $version;
68 }
69 $this->data = json_decode(file_get_contents('php://input'));
70 }
71
72 /**
73 * @param $token
74 * @param $version
75 * @param null $also_version
76 * @return vk_api
77 *
78 * @throws VkApiException
79 */
80 public static function create($token, $version, $also_version = null) {
81 return new self($token, $version, $also_version);
82 }
83
84 /**
85 * @param $str
86 * @return vk_api
87 */
88 public function setConfirm($str) {
89 if (isset($this->data->type) && $this->data->type == 'confirmation') { //Если vk запрашивает ключ
90 exit($str); //Завершаем скрипт отправкой ключа
91 }
92 return $this;
93 }
94
95 /**
96 * @param null $id
97 * @param null $message
98 * @param null $payload
99 * @param null $user_id
100 * @param null $type
101 * @param null $data
102 * @return array|mixed|null
103 */
104 public function initVars(&$id = null, &$message = null, &$payload = null, &$user_id = null, &$type = null, &$data = null) {
105 if (!$this->debug_mode)
106 $this->sendOK();
107 $data = $this->data;
108 $data_backup = $this->data;
109 $type = isset($data->type) ? $data->type : null;
110 if(isset($data->object->message) and $type == 'message_new') {
111 $data->object = $data->object->message; //какая-то дичь с ссылками, но $this->data теперь тоже переопределился
112 }
113 $id = isset($data->object->peer_id) ? $data->object->peer_id : null;
114 $message = isset($data->object->text) ? $data->object->text : null;
115 $payload = isset($data->object->payload) ? json_decode($data->object->payload, true) : null;
116 $user_id = isset($data->object->from_id) ? $data->object->from_id : null;
117 $data = $data_backup;
118 return $data_backup;
119 }
120
121 /**
122 * @return bool
123 */
124 public function sendOK() {
125 set_time_limit(0);
126 ini_set('display_errors', 'Off');
127 ob_end_clean();
128
129 // для Nginx
130 if (is_callable('fastcgi_finish_request')) {
131 echo 'ok';
132 session_write_close();
133 fastcgi_finish_request();
134 return True;
135 }
136 // для Apache
137 ignore_user_abort(true);
138
139 ob_start();
140 header('Content-Encoding: none');
141 header('Content-Length: 2');
142 header('Connection: close');
143 echo 'ok';
144 ob_end_flush();
145 flush();
146 return True;
147 }
148
149 /**
150 * @param $message
151 * @param array $params
152 * @return bool|mixed
153 * @throws VkApiException
154 */
155 public function reply($message, $params = []) {
156 if ($this->data != []) {
157 $message = $this->placeholders($this->data->object->peer_id, $message);
158 return $this->request('messages.send', ['message' => $message, 'peer_id' => $this->data->object->peer_id] + $params);
159 } else {
160 throw new VkApiException('Вк не прислал callback, возможно вы пытаетесь запустить скрипт с локалки');
161 }
162 }
163
164 public function forward($id, $id_messages, $params = []) {
165 $forward_messages = (is_array($id_messages)) ? join(',', $id_messages) : $id_messages;
166 return $this->request('messages.send', ['peer_id' => $id, 'forward_messages' => $forward_messages] + $params);
167 }
168
169 public function sendAllChats($message, $params = []) {
170 unset($this->request_ignore_error[array_search(10, $this->request_ignore_error)]); //убираем код 10 из исключений
171 $i = 0;
172 $count = 0;
173 print "Начинаю перебор всех бесед...\n";
174 while (true) {
175 print(++$i . " ");
176 try {
177 $this->sendMessage(2000000000 + $i, $message, $params);
178 $count++;
179 } catch (VkApiException $e) {
180 if ($e->getCode() == 10) {
181 print "\nВсего было разослано в $count бесед";
182 break;
183 }
184 }
185 }
186 }
187
188 protected function placeholders($id, $message) {
189 if($id >= 2000000000) {
190 $id = isset($this->data->object->from_id) ? $this->data->object->from_id : null;
191 }
192 if($id == null) {
193 print "Попытка использовать заполнители при передаче id беседы";
194 return $message;
195 } else {
196 if (strpos($message, '%') !== false) {
197 $data = $this->userInfo($id);
198 $f = $data['first_name'];
199 $l = $data['last_name'];
200 $tag = ['%fn%', '%ln%', '%full%', '%a_fn%', '%a_ln%', '%a_full%'];
201 $replace = [$f, $l, "$f $l", "@id{$id}($f)", "@id{$id}($l)", "@id{$id}($f $l)"];
202 return str_replace($tag, $replace, $message);
203 } else
204 return $message;
205 }
206 }
207
208 /**
209 * @param $method
210 * @param array $params
211 * @return bool|mixed
212 * @throws VkApiException
213 */
214 public function request($method, $params = []) {
215 list($method, $params) = $this->editRequestParams($method, $params);
216 $url = 'https://api.vk.com/method/' . $method;
217 $params['access_token'] = $this->token;
218 $params['v'] = $this->version;
219 $params['random_id'] = rand(-2147483648, 2147483647);
220
221 while (True) {
222 try {
223 return $this->request_core($url, $params);
224 } catch (VkApiException $e) {
225 if (in_array($e->getCode(), $this->request_ignore_error)) {
226 sleep(1);
227 continue;
228 }
229 else
230 throw new VkApiException($e->getMessage(), $e->getCode());
231 }
232 }
233 return false;
234 }
235
236 /**
237 * @param $method
238 * @param $params
239 * @return array
240 */
241 protected function editRequestParams($method, $params) {
242 return [$method, $params];
243 }
244
245 /**
246 * @param $url
247 * @param array $params
248 * @return mixed
249 * @throws VkApiException
250 */
251 private function request_core($url, $params = []) {
252 if (function_exists('curl_init')) {
253 $ch = curl_init();
254 curl_setopt($ch, CURLOPT_HTTPHEADER, [
255 "Content-Type:multipart/form-data"
256 ]);
257 curl_setopt($ch, CURLOPT_URL, $url);
258 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
259 curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
260 curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
261 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
262 $result = json_decode(curl_exec($ch), True);
263 curl_close($ch);
264 } else {
265 $result = json_decode(file_get_contents($url, true, stream_context_create([
266 'http' => [
267 'method' => 'POST',
268 'header' => "Content-type: application/x-www-form-urlencoded\r\n",
269 'content' => http_build_query($params)
270 ]
271 ])), true);
272 }
273 if (!isset($result))
274 $this->request_core($url, $params);
275 if (isset($result['error'])) {
276 throw new VkApiException(json_encode($result), $result['error']['error_code']);
277 }
278 if (isset($result['response']))
279 return $result['response'];
280 else
281 return $result;
282 }
283
284 /**
285 * @param $message
286 * @param null $keyboard
287 * @param string $filter
288 * @param array $params
289 * @throws VkApiException
290 */
291 public function sendAllDialogs($message, $keyboard = null, $filter = 'all', $params = []) {
292 $ids = [];
293 for ($count_all = 1, $offset = 0; $offset <= $count_all; $offset += 200) {
294 $members = $this->request('messages.getConversations', ['count' => 200, 'offset' => $offset, 'filter' => $filter]);//'filter' => 'unread'
295 if ($count_all != 1)
296 $offset += $members['count'] - $count_all;
297 $count_all = $members['count'];
298
299 foreach ($members["items"] as $user)
300 if ($user['conversation']["can_write"]["allowed"] == true)
301 $ids [] = $user['conversation']['peer']['id'];
302 }
303 $ids = array_chunk($ids, 100);
304 foreach ($ids as $ids_chunk) {
305 try {
306 $this->request('messages.send', ['user_ids' => join(',', $ids_chunk), 'message' => $message, 'keyboard' => $keyboard] + $params);
307 } catch (Exception $e) {
308 continue;
309 }
310 }
311 }
312
313 /**
314 * @param $id
315 * @param null $n
316 * @return string
317 * @throws VkApiException
318 */
319 public function getAlias($id, $n = null) { //получить обращение к юзеру или группе
320 if (!is_numeric($id)) { //если короткая ссылка
321 $obj = $this->request('utils.resolveScreenName', ['screen_name' => $id]); //узнаем, кому принадлежит, сообществу или юзеру
322 $id = ($obj["type"] == 'group') ? -$obj['object_id'] : $obj['object_id'];
323 }
324 if (isset($n)) {
325 if (is_string($n)) {
326 if ($id < 0)
327 return "@club" . ($id * -1) . "($n)";
328 else
329 return "@id{$id}($n)";
330 } else {
331 if ($id < 0) {
332 $id = -$id;
333 $group_name = $this->request('groups.getById', ['group_id' => $id])[0]['name'];
334 return "@club{$id}({$group_name})";
335 } else {
336 $info = $this->userInfo($id);
337 if ($n)
338 return "@id{$id}($info[first_name] $info[last_name])";
339 else
340 return "@id{$id}($info[first_name])";
341 }
342 }
343 } else {
344 if ($id < 0)
345 return "@club" . ($id * -1);
346 else
347 return "@id{$id}";
348 }
349 }
350
351 /**
352 * @param null $user_url
353 * @param array $scope
354 * @return mixed
355 * @throws VkApiException
356 */
357 public function userInfo($user_url = '', $scope = []) {
358 $scope = ["fields" => join(",", $scope)];
359 if (isset($user_url)) {
360 $user_url = preg_replace("!.*?/!", '', $user_url);
361 $user_url = ($user_url == '') ? [] : ["user_ids" => $user_url];
362 }
363 try {
364 return current($this->request('users.get', $user_url + $scope));
365 } catch (Exception $e) {
366 return false;
367 }
368 }
369
370
371 /**
372 * @param $chat_id
373 * @param $user_id
374 * @return bool|null|string
375 * @throws VkApiException
376 */
377 public function isAdmin($user_id, $chat_id) { //возвращает привелегию по id
378 try {
379 $members = $this->request('messages.getConversationMembers', ['peer_id' => $chat_id])['items'];
380 } catch (\Exception $e) {
381 throw new VkApiException('Бот не админ в этой беседе, или бота нет в этой беседе');
382 }
383 foreach ($members as $key) {
384 if ($key['member_id'] == $user_id)
385 return (isset($key["is_owner"])) ? 'owner' : ((isset($key["is_admin"])) ? 'admin' : false);
386 }
387 return null;
388 }
389
390 /**
391 * @param $id
392 * @param $message
393 * @param array $params
394 * @return bool|mixed
395 * @throws VkApiException
396 */
397 public function sendMessage($id, $message, $params = []) {
398 if ($id < 1)
399 return 0;
400 $message = $this->placeholders($id, $message);
401 return $this->request('messages.send', ['message' => $message, 'peer_id' => $id] + $params);
402 }
403
404 /**
405 *
406 */
407 public function debug() {
408 ini_set('error_reporting', E_ALL);
409 ini_set('display_errors', 1);
410 ini_set('display_startup_errors', 1);
411 echo 'ok';
412 $this->debug_mode = 1;
413 }
414
415 /**
416 * @param $id
417 * @param $message
418 * @param array $buttons
419 * @param bool $inline
420 * @param bool $one_time
421 * @param array $params
422 * @return mixed
423 * @throws VkApiException
424 */
425 public function sendButton($id, $message, $buttons = [], $inline = false, $one_time = False, $params = []) {
426 $keyboard = $this->generateKeyboard($buttons, $inline, $one_time);
427 $message = $this->placeholders($id, $message);
428 return $this->request('messages.send', ['message' => $message, 'peer_id' => $id, 'keyboard' => $keyboard] + $params);
429 }
430
431 public function buttonLocation($payload = null) {
432 return ['location', $payload];
433 }
434
435 public function buttonPayToGroup($group_id, $amount, $description = null, $data = null, $payload = null) {
436 return ['vkpay', $payload, 'pay-to-group', $group_id, $amount, $description, $data];
437 }
438
439 public function buttonPayToUser($user_id, $amount, $description = null, $payload = null) {
440 return ['vkpay', $payload, 'pay-to-user', $user_id, $amount, $description];
441 }
442
443 public function buttonDonateToGroup($group_id, $payload = null) {
444 return ['vkpay', $payload, 'transfer-to-group', $group_id];
445 }
446
447 public function buttonDonateToUser($user_id, $payload = null) {
448 return ['vkpay', $payload, 'transfer-to-user', $user_id];
449 }
450
451 public function buttonApp($text, $app_id, $owner_id = null, $hash = null, $payload = null) {
452 return ['open_app', $payload, $text, $app_id, $owner_id, $hash];
453 }
454
455 public function buttonOpenLink($text, $link, $payload = null) {
456 return ['open_link', $payload, $text, $link];
457 }
458
459 public function buttonText($text, $color, $payload = null) {
460 return ['text', $payload, $text, $color];
461 }
462
463 /**
464 * @param array $buttons
465 * @param bool $inline
466 * @param bool $one_time
467 * @return array|false|string
468 */
469 public function generateKeyboard($buttons = [], $inline = false, $one_time = False) {
470 $keyboard = [];
471 $i = 0;
472 foreach ($buttons as $button_str) {
473 $j = 0;
474 foreach ($button_str as $button) {
475 $keyboard[$i][$j]["action"]["type"] = $button[0];
476 if ($button[1] != null)
477 $keyboard[$i][$j]["action"]["payload"] = json_encode($button[1], JSON_UNESCAPED_UNICODE);
478 switch ($button[0]) {
479 case 'text': {
480 $color = $this->replaceColor($button[3]);
481 $keyboard[$i][$j]["color"] = $color;
482 $keyboard[$i][$j]["action"]["label"] = $button[2];
483 break;
484 }
485 case 'vkpay': {
486 $keyboard[$i][$j]["action"]["hash"] = "action={$button[2]}";
487 $keyboard[$i][$j]["action"]["hash"] .= ($button[3] < 0) ? "&group_id=".$button[3]*-1 : "&user_id={$button[3]}";
488 $keyboard[$i][$j]["action"]["hash"] .= (isset($button[4])) ? "&amount={$button[4]}" : '';
489 $keyboard[$i][$j]["action"]["hash"] .= (isset($button[5])) ? "&description={$button[5]}" : '';
490 $keyboard[$i][$j]["action"]["hash"] .= (isset($button[6])) ? "&data={$button[6]}" : '';
491 $keyboard[$i][$j]["action"]["hash"] .= "&aid=1";
492 break;
493 }
494 case 'open_app': {
495 $keyboard[$i][$j]["action"]["label"] = $button[2];
496 $keyboard[$i][$j]["action"]["app_id"] = $button[3];
497 if(isset($button[4]))
498 $keyboard[$i][$j]["action"]["owner_id"] = $button[4];
499 if(isset($button[5]))
500 $keyboard[$i][$j]["action"]["hash"] = $button[5];
501 break;
502 }
503 case 'open_link': {
504 $keyboard[$i][$j]["action"]["label"] = $button[2];
505 $keyboard[$i][$j]["action"]["link"] = $button[3];
506 break;
507 }
508 }
509 $j++;
510 }
511 $i++;
512 }
513 $keyboard = ["one_time" => $one_time, "buttons" => $keyboard, 'inline' => $inline];
514 $keyboard = json_encode($keyboard, JSON_UNESCAPED_UNICODE);
515 return $keyboard;
516 }
517
518 /**
519 * @param $color
520 * @return string
521 */
522 private function replaceColor($color) {
523 switch ($color) {
524 case 'red':
525 $color = 'negative';
526 break;
527 case 'green':
528 $color = 'positive';
529 break;
530 case 'white':
531 $color = 'default';
532 break;
533 case 'blue':
534 $color = 'primary';
535 break;
536 }
537 return $color;
538 }
539
540 /**
541 * @param $group_url
542 * @return mixed
543 * @throws VkApiException
544 */
545 public function groupInfo($group_url) {
546 $group_url = preg_replace("!.*?/!", '', $group_url);
547 return current($this->request('groups.getById', ["group_ids" => $group_url]));
548 }
549
550 /**
551 * @param $id
552 * @param $local_file_path
553 * @param array $params
554 * @return mixed
555 * @throws VkApiException
556 */
557 public function sendImage($id, $local_file_path, $params = []) {
558 $upload_file = $this->uploadImage($id, $local_file_path);
559 return $this->request('messages.send', ['attachment' => "photo" . $upload_file[0]['owner_id'] . "_" . $upload_file[0]['id'], 'peer_id' => $id] + $params);
560 }
561
562 /**
563 * @param $id
564 * @param $local_file_path
565 * @return mixed
566 * @throws VkApiException
567 */
568 private function uploadImage($id, $local_file_path) {
569 $upload_url = $this->getUploadServerMessages($id, 'photo')['upload_url'];
570 for ($i = 0; $i < $this->try_count_resend_file; ++$i) {
571 try {
572 $answer_vk = json_decode($this->sendFiles($upload_url, $local_file_path, 'photo'), true);
573 return $this->savePhoto($answer_vk['photo'], $answer_vk['server'], $answer_vk['hash']);
574 } catch (VkApiException $e) {
575 sleep(1);
576 $exception = json_decode($e->getMessage(), true);
577 if ($exception['error']['error_code'] != 121)
578 throw new VkApiException($e->getMessage(), $exception['error']['error_code']);
579 }
580 }
581 $answer_vk = json_decode($this->sendFiles($upload_url, $local_file_path, 'photo'), true);
582 return $this->savePhoto($answer_vk['photo'], $answer_vk['server'], $answer_vk['hash']);
583 }
584
585 /**
586 * @param $peer_id
587 * @param string $selector
588 * @return mixed|null
589 * @throws VkApiException
590 */
591 private function getUploadServerMessages($peer_id, $selector = 'doc') {
592 $result = null;
593 if ($selector == 'doc')
594 $result = $this->request('docs.getMessagesUploadServer', ['type' => 'doc', 'peer_id' => $peer_id]);
595 else if ($selector == 'photo')
596 $result = $this->request('photos.getMessagesUploadServer', ['peer_id' => $peer_id]);
597 else if ($selector == 'audio_message')
598 $result = $this->request('docs.getMessagesUploadServer', ['type' => 'audio_message', 'peer_id' => $peer_id]);
599 return $result;
600 }
601
602 private function uploadVoice($id, $local_file_path) {
603 $upload_url = $this->getUploadServerMessages($id, 'audio_message')['upload_url'];
604 $answer_vk = json_decode($this->sendFiles($upload_url, $local_file_path, 'file'), true);
605 return $this->saveDocuments($answer_vk['file'], 'voice');
606 }
607
608 public function sendVoice($id, $local_file_path, $params = []) {
609 $upload_file = $this->uploadVoice($id, $local_file_path);
610 return $this->request('messages.send', ['attachment' => "doc" . $upload_file['audio_message']['owner_id'] . "_" . $upload_file['audio_message']['id'], 'peer_id' => $id] + $params);
611 }
612
613 /**
614 * @param $url
615 * @param $local_file_path
616 * @param string $type
617 * @return mixed
618 * @throws VkApiException
619 */
620 protected function sendFiles($url, $local_file_path, $type = 'file') {
621 $post_fields = [
622 $type => new CURLFile(realpath($local_file_path))
623 ];
624
625 for ($i = 0; $i < $this->try_count_resend_file; ++$i) {
626
627 $ch = curl_init();
628 curl_setopt($ch, CURLOPT_HTTPHEADER, [
629 "Content-Type:multipart/form-data"
630 ]);
631 curl_setopt($ch, CURLOPT_URL, $url);
632 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
633 curl_setopt($ch, CURLOPT_POSTFIELDS, $post_fields);
634 curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
635 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
636 $output = curl_exec($ch);
637 if ($output != '')
638 break;
639 else
640 sleep(1);
641 }
642 if ($output == '')
643 throw new VkApiException('Не удалось загрузить файл на сервер');
644 return $output;
645 }
646
647 /**
648 * @param $photo
649 * @param $server
650 * @param $hash
651 * @return mixed
652 * @throws VkApiException
653 */
654 private function savePhoto($photo, $server, $hash) {
655 return $this->request('photos.saveMessagesPhoto', ['photo' => $photo, 'server' => $server, 'hash' => $hash]);
656 }
657
658 /**
659 * @param $groupID
660 * @param $local_file_path
661 * @param null $title
662 * @return mixed
663 *
664 * @throws VkApiException
665 */
666 public function uploadDocsGroup($groupID, $local_file_path, $title = null) {
667 return $this->uploadDocs($groupID, $local_file_path, $title);
668 }
669
670 /**
671 * @param $id
672 * @param $local_file_path
673 * @param null $title
674 * @return mixed
675 * @throws VkApiException
676 */
677 private function uploadDocs($id, $local_file_path, $title = null) {
678 if (!isset($title))
679 $title = preg_replace("!.*?/!", '', $local_file_path);
680 $upload_url = $this->getUploadServerPost($id)['upload_url'];
681 $answer_vk = json_decode($this->sendFiles($upload_url, $local_file_path), true);
682 $upload_file = $this->saveDocuments($answer_vk['file'], $title);
683 return $upload_file;
684 }
685
686 /**
687 * @param array $peer_id
688 * @return mixed
689 * @throws VkApiException
690 */
691 private function getUploadServerPost($peer_id = []) {
692 if ($peer_id < 0)
693 $peer_id = ['group_id' => $peer_id * -1];
694 else
695 $peer_id = [];
696 $result = $this->request('docs.getUploadServer', $peer_id);
697 return $result;
698 }
699
700 /**
701 * @param $file
702 * @param $title
703 * @return mixed
704 * @throws VkApiException
705 */
706 private function saveDocuments($file, $title) {
707 return $this->request('docs.save', ['file' => $file, 'title' => $title]);
708 }
709
710 /**
711 * @param $id
712 * @param $local_file_path
713 * @param null $title
714 * @param array $params
715 * @return bool|mixed
716 * @throws VkApiException
717 */
718 public function sendDocMessage($id, $local_file_path, $title = null, $params = []) {
719 $upload_file = current($this->uploadDocsMessages($id, $local_file_path, $title));
720 if ($id != 0 and $id != '0') {
721 return $this->request('messages.send', ['attachment' => "doc" . $upload_file['owner_id'] . "_" . $upload_file['id'], 'peer_id' => $id] + $params);
722 } else {
723 return true;
724 }
725 }
726
727 /**
728 * @param $id
729 * @param $local_file_path
730 * @param null $title
731 * @return mixed
732 * @throws VkApiException
733 */
734 private function uploadDocsMessages($id, $local_file_path, $title = null) {
735 if (!isset($title))
736 $title = preg_replace("!.*?/!", '', $local_file_path);
737 $upload_url = $this->getUploadServerMessages($id)['upload_url'];
738 $answer_vk = json_decode($this->sendFiles($upload_url, $local_file_path), true);
739 $upload_file = $this->saveDocuments($answer_vk['file'], $title);
740 return $upload_file;
741 }
742
743 /**
744 * @param $id
745 * @param array $message
746 * @param array $props
747 * @param array $media
748 * @return mixed
749 * @throws VkApiException
750 */
751 public function createPost($id, $message = [], $props = [], $media = []) {
752 $send_attachment = [];
753
754 foreach ($media as $selector => $massive) {
755 switch ($selector) {
756 case "images":
757 foreach ($massive as $image) {
758 $upload_url = $this->getWallUploadServer($id);
759 for ($i = 0; $i <= $this->try_count_resend_file; ++$i) {
760 try {
761 $answer_vk = json_decode($this->sendFiles($upload_url['upload_url'], $image, 'photo'), true);
762 $upload_file = $this->savePhotoWall($answer_vk['photo'], $answer_vk['server'], $answer_vk['hash'], $id);
763 $send_attachment[] = "photo" . $upload_file[0]['owner_id'] . "_" . $upload_file[0]['id'];
764 break;
765 } catch (VkApiException $e) {
766 if ($i == $this->try_count_resend_file)
767 throw new VkApiException($e->getMessage(), $e->getCode());
768 sleep(1);
769 $exception = json_decode($e->getMessage(), true);
770 if ($exception['error']['error_code'] != 121)
771 throw new VkApiException($e->getMessage(), $e->getCode());
772 }
773 }
774 }
775 break;
776 case "docs":
777 foreach ($massive as $docs) {
778 $upload_file = $this->uploadDocsUser($docs);
779 if (isset($upload_file['type']))
780 $upload_file = $upload_file[$upload_file['type']];
781 else
782 $upload_file = current($upload_file);
783 $send_attachment[] = "doc" . $upload_file['owner_id'] . "_" . $upload_file['id'];
784 }
785 break;
786 case "other":
787 break;
788 }
789 }
790 if (count($send_attachment) != 0)
791 $send_attachment = ["attachment" => join(',', $send_attachment)];
792 if (is_string($message))
793 $message = ['message' => $message];
794 return $this->request('wall.post', ['owner_id' => $id] + $message + $props + $send_attachment);
795 }
796
797 /**
798 * @param $owner_id , $post_id, $message
799 * @param $post_id
800 * @param $message
801 * @return mixed
802 * @throws VkApiException
803 */
804 public function sendWallComment($owner_id, $post_id, $message) {
805 return $this->request('wall.createComment', ['owner_id' => $owner_id, 'post_id' => $post_id, 'message' => $message]);
806 }
807
808 /**
809 * @param $id
810 * @return mixed
811 * @throws VkApiException
812 */
813 private function getWallUploadServer($id) {
814 if ($id < 0) {
815 $id *= -1;
816 return $this->request('photos.getWallUploadServer', ['group_id' => $id]);
817 } else {
818 return $this->request('photos.getWallUploadServer', ['user_id' => $id]);
819 }
820 }
821
822 /**
823 * @param $photo
824 * @param $server
825 * @param $hash
826 * @param $id
827 * @return mixed
828 * @throws VkApiException
829 */
830 private function savePhotoWall($photo, $server, $hash, $id) {
831 if ($id < 0) {
832 $id *= -1;
833 return $this->request('photos.saveWallPhoto', ['photo' => $photo, 'server' => $server, 'hash' => $hash, 'group_id' => $id]);
834 } else {
835 return $this->request('photos.saveWallPhoto', ['photo' => $photo, 'server' => $server, 'hash' => $hash, 'user_id' => $id]);
836 }
837 }
838
839 /**
840 * @param $local_file_path
841 * @param null $title
842 * @return mixed
843 *
844 * @throws VkApiException
845 */
846 public function uploadDocsUser($local_file_path, $title = null) {
847 return $this->uploadDocs([], $local_file_path, $title);
848 }
849
850 /**
851 * @param $id
852 * @param array $message
853 * @param array $props
854 * @param array $media
855 * @param array $keyboard
856 * @return mixed
857 * @throws VkApiException
858 */
859 public function createMessages($id, $message = [], $props = [], $media = [], $keyboard = []) {
860 if ($id < 1)
861 return 0;
862 $send_attachment = [];
863
864 foreach ($media as $selector => $massiv) {
865 switch ($selector) {
866 case "images":
867 foreach ($massiv as $image) {
868 $upload_file = $upload_file = $this->uploadImage($id, $image);
869 $send_attachment[] = "photo" . $upload_file[0]['owner_id'] . "_" . $upload_file[0]['id'];
870 }
871 break;
872 case "docs":
873 foreach ($massiv as $document) {
874 $upload_file = $this->uploadDocsMessages($id, $document['path'], $document['title']);
875 if (isset($upload_file['type']))
876 $upload_file = $upload_file[$upload_file['type']];
877 else
878 $upload_file = current($upload_file);
879 $send_attachment[] = "doc" . $upload_file['owner_id'] . "_" . $upload_file['id'];
880 }
881 break;
882 case "voice":
883 foreach ($massiv as $voice) {
884 $upload_file = $this->uploadVoice($id, $voice);
885 $send_attachment[] = "doc" . $upload_file['audio_message']['owner_id'] . "_" . $upload_file['audio_message']['id'];
886 }
887 break;
888 case "other":
889 break;
890 }
891 }
892 if (count($send_attachment) != 0)
893 $send_attachment = ["attachment" => join(',', $send_attachment)];
894 if (is_string($message))
895 $message = ['message' => $message];
896 if ($keyboard != [])
897 $keyboard = ['keyboard' => $this->generateKeyboard($keyboard['keyboard'], $keyboard['inline'], $keyboard['one_time'])];
898 return $this->request('messages.send', ['peer_id' => $id] + $message + $props + $send_attachment + $keyboard);
899 }
900
901 /**
902 * @param array $id
903 * @param int $extended
904 * @param array $props
905 * @return mixed
906 * @throws VkApiException
907 */
908 public function getGroupsUser($id = [], $extended = 1, $props = []) {
909 if (is_numeric($id))
910 $id = ['user_id' => $id];
911 if (!is_array($props))
912 $props = [];
913 if ($extended == 1)
914 $extended = ['extended' => 1];
915 else
916 $extended = [];
917 return $this->request('groups.get', $id + $props + $extended);
918 }
919
920 /**
921 * @param $var
922 * @throws VkApiException
923 */
924 public function setTryCountResendFile($var) {
925 if (is_integer($var))
926 $this->try_count_resend_file = $var;
927 else
928 throw new VkApiException("Параметр должен быть числовым");
929 }
930
931 /**
932 * @param $var
933 * @throws VkApiException
934 */
935 public function setRequestIgnoreError($var) {
936 if (is_array($var))
937 $this->request_ignore_error = $var;
938 else if (is_integer($var))
939 $this->request_ignore_error = [$var];
940 else
941 throw new VkApiException("Параметр должен быть числовым либо массивом");
942 }
943
944 /**
945 * @param $id
946 * @return mixed
947 */
948 public function dateRegistration($id) {
949 $site = file_get_contents("https://vk.com/foaf.php?id={$id}");
950 preg_match('<ya:created dc:date="(.*?)">', $site, $data);
951 $data = explode('T', $data[1]);
952 $date = date("d.m.Y", strtotime($data[0]));
953 $time = mb_substr($data[1], 0, 8);
954 return "$time $date";
955 }
956
957 /**
958 * @return array
959 */
960 protected function copyAllDataclass() {
961 return [$this->token, $this->version, $this->auth, $this->request_ignore_error, $this->try_count_resend_file];
962 }
963
964 /**
965 * @param $id_vk_vars
966 */
967 protected function setAllDataclass($id_vk_vars) {
968 list($this->token, $this->version, $this->auth, $this->request_ignore_error, $this->try_count_resend_file) = $id_vk_vars;
969 }
970}
971
972
973//include "vk_api.php";
974
975const VK_KEY = "de7b23d8770f4a657d90fa9e31448962e32bfdea94a0724eff7f01260625050887f6b12b48fd913e34b75"; // Токен сообщества
976const ACCESS_KEY = "e7b34fd6"; // Тот самый ключ из сообщества
977const VERSION = "5.81"; // Версия API VK
978
979$vk = new vk_api(VK_KEY, VERSION); // создание экземпляра класса работы с api, принимает токен и версию api
980$data = json_decode(file_get_contents('php://input')); //Получает и декодирует JSON пришедший из ВК
981if ($data->type == 'confirmation') { //Если vk запрашивает ключ
982 exit(ACCESS_KEY); //Завершаем скрипт отправкой ключа
983}
984$vk->sendOK(); //Говорим vk, что мы приняли callback
985
986$id = $data->object->from_id; // Узнаем ID пользователя, кто написал нам
987$message = $data->object->text; // Само сообщение от пользователя
988
989if ($data->type == 'message_new') {
990 if ($message == '!бот') {
991 $vk->sendMessage($id, "Привет :-)"); // Отправляем ответ
992 }
993}
994