├── README.md ├── static └── cat.jpeg └── www ├── api ├── vk_api.php └── yandex_api.php ├── bot └── bot.php ├── config.php ├── global.php └── index.php /README.md: -------------------------------------------------------------------------------- 1 | # Бот для VK 2 | 3 | Пример простого бота для ВКонтакте на PHP. Обработка событий с использованием Callback API, голосовые сообщения с помощью Яндекс SpeechKit. 4 | 5 | Сообщество бота: https://vk.com/botexample. Бот отправляет в ответ на любое сообщение картинку и голосовое сообщение с именем собеседника. 6 | 7 | ## Подготовка к использованию 8 | Укажите свои данные в [config.php](https://github.com/VKCOM/bot-example-php/blob/master/www/config.php). 9 | Ключ доступа к API и код подтверждения для Callback API Вы можете получить в настройках сообщества. Подробнее о получении ключа доступа для Яндекс SpeechKit можно прочитать [здесь](https://tech.yandex.ru/speechkit/). 10 | 11 | ## Описание файлов 12 | ### [index.php](https://github.com/VKCOM/bot-example-php/blob/master/www/index.php) 13 | Обработка событий Callback API. В нашем примере обрабатываются два события: 14 | - *confirmation* — уведомление для подтверждения адреса сервера; 15 | - *new_message* — уведомление о входящем сообщении. 16 | 17 | Подробную информацию о типах событий и формате уведомлений Вы найдёте [в документации ВК API](https://vk.com/dev/callback_api). 18 | 19 | ### [bot/bot.php](https://github.com/VKCOM/bot-example-php/blob/master/www/bot/bot.php) 20 | Отправка сообщений с вложениями. 21 | 22 | ### [api/vk_api.php](https://github.com/VKCOM/bot-example-php/blob/master/www/api/vk_api.php) 23 | Функции для работы с методами API ВКонтакте 24 | 25 | ### [api/yandex_api.php](https://github.com/VKCOM/bot-example-php/blob/master/www/api/yandex_api.php) 26 | Функции для работы с API Яндекс SpeechKit для генерация голосовых сообщений. 27 | -------------------------------------------------------------------------------- /static/cat.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/VKCOM/bot-example-php/15da2241491d785130eb0e6962f9fec457c1379a/static/cat.jpeg -------------------------------------------------------------------------------- /www/api/vk_api.php: -------------------------------------------------------------------------------- 1 | $peer_id, 9 | 'message' => $message, 10 | 'attachment' => implode(',', $attachments) 11 | )); 12 | } 13 | 14 | function vkApi_usersGet($user_id) { 15 | return _vkApi_call('users.get', array( 16 | 'user_id' => $user_id, 17 | )); 18 | } 19 | 20 | function vkApi_photosGetMessagesUploadServer($peer_id) { 21 | return _vkApi_call('photos.getMessagesUploadServer', array( 22 | 'peer_id' => $peer_id, 23 | )); 24 | } 25 | 26 | function vkApi_photosSaveMessagesPhoto($photo, $server, $hash) { 27 | return _vkApi_call('photos.saveMessagesPhoto', array( 28 | 'photo' => $photo, 29 | 'server' => $server, 30 | 'hash' => $hash, 31 | )); 32 | } 33 | 34 | function vkApi_docsGetMessagesUploadServer($peer_id, $type) { 35 | return _vkApi_call('docs.getMessagesUploadServer', array( 36 | 'peer_id' => $peer_id, 37 | 'type' => $type, 38 | )); 39 | } 40 | 41 | function vkApi_docsSave($file, $title) { 42 | return _vkApi_call('docs.save', array( 43 | 'file' => $file, 44 | 'title' => $title, 45 | )); 46 | } 47 | 48 | function _vkApi_call($method, $params = array()) { 49 | $params['access_token'] = VK_API_ACCESS_TOKEN; 50 | $params['v'] = VK_API_VERSION; 51 | 52 | $query = http_build_query($params); 53 | $url = VK_API_ENDPOINT.$method.'?'.$query; 54 | 55 | $curl = curl_init($url); 56 | curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); 57 | $json = curl_exec($curl); 58 | $error = curl_error($curl); 59 | if ($error) { 60 | log_error($error); 61 | throw new Exception("Failed {$method} request"); 62 | } 63 | 64 | curl_close($curl); 65 | 66 | $response = json_decode($json, true); 67 | if (!$response || !isset($response['response'])) { 68 | log_error($json); 69 | throw new Exception("Invalid response for {$method} request"); 70 | } 71 | 72 | return $response['response']; 73 | } 74 | 75 | function vkApi_upload($url, $file_name) { 76 | if (!file_exists($file_name)) { 77 | throw new Exception('File not found: '.$file_name); 78 | } 79 | 80 | $curl = curl_init($url); 81 | curl_setopt($curl, CURLOPT_POST, true); 82 | curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); 83 | curl_setopt($curl, CURLOPT_POSTFIELDS, array('file' => new CURLfile($file_name))); 84 | $json = curl_exec($curl); 85 | $error = curl_error($curl); 86 | if ($error) { 87 | log_error($error); 88 | throw new Exception("Failed {$url} request"); 89 | } 90 | 91 | curl_close($curl); 92 | 93 | $response = json_decode($json, true); 94 | if (!$response) { 95 | throw new Exception("Invalid response for {$url} request"); 96 | } 97 | 98 | return $response; 99 | } 100 | -------------------------------------------------------------------------------- /www/api/yandex_api.php: -------------------------------------------------------------------------------- 1 | 'opus', 15 | 'lang' => 'ru-RU', 16 | 'speaker' => 'jane', 17 | 'key' => YANDEX_API_KEY, 18 | 'emotion' => 'good', 19 | 'text' => $text, 20 | )); 21 | 22 | $url = YANDEX_API_ENDPOINT.'?'.$query; 23 | 24 | $curl_handler = curl_init($url); 25 | curl_setopt($curl_handler, CURLOPT_FILE, $file_handler); 26 | curl_exec($curl_handler); 27 | 28 | $error = curl_error($curl_handler); 29 | if ($error) { 30 | log_error($error); 31 | throw new Exception("Failed {$url} request"); 32 | } 33 | 34 | curl_close($curl_handler); 35 | fclose($file_handler); 36 | 37 | return $file_name; 38 | } 39 | 40 | -------------------------------------------------------------------------------- /www/bot/bot.php: -------------------------------------------------------------------------------- 1 |