Advertisement
tristamoff

Untitled

Feb 22nd, 2017
90
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 7.67 KB | None | 0 0
  1. <?php
  2.  
  3. //запись в лог
  4. function teleToLog($log) {
  5.   $myFile = 'log.txt';
  6.   $fh = fopen($myFile, 'a') or die('can\'t open file');
  7.   if ((is_array($log)) || (is_object($log))) {
  8.     $updateArray = print_r($log, TRUE);
  9.     fwrite($fh, $updateArray."\n");
  10.   } else {
  11.     fwrite($fh, $log . "\n");
  12.   }
  13.   fclose($fh);
  14. }
  15.  
  16. //обработка запроса от пользователя
  17. function getUserRequest($text, $chat_id) {
  18.   $resp = [];
  19.   $resp['chat_id'] = $chat_id;
  20.   $resp['text'] = 'Приветствую вас';
  21.   $menu = array(
  22.     'keyboard' => array(
  23.       array(
  24.         array('text' => json_decode('"\uD83C\uDF04"') . ' Фотография')
  25.       ),
  26.       array(
  27.         array('text' => json_decode('"\uD83D\uDCDD"') . ' Образование')
  28.       ),
  29.       array(
  30.         array('text' => json_decode('"\uD83C\uDFA8"') . ' Творчество')
  31.       ),
  32.     )
  33.   );
  34.   $resp['reply_markup'] = json_encode($menu);
  35.   $data = commIsHello($text);
  36.   if (!empty($data)) {
  37.     $resp = array_merge($resp, $data);
  38.     requestToTelegram($resp);
  39.     return TRUE;
  40.   }
  41.   $data = commIsUser($text);
  42.   if (!empty($data)) {
  43.     $resp = array_merge($resp, $data);
  44.     requestToTelegram($resp);
  45.     return TRUE;
  46.   }
  47.   $data = commIsTag($text);
  48.   if (!empty($data)) {
  49.     $resp = array_merge($resp, $data);
  50.     requestToTelegram($resp);
  51.     return TRUE;
  52.   }
  53.  
  54.   requestToTelegram($resp);
  55. }
  56.  
  57. //проверка на тэг
  58. function commIsTag($text) {
  59.   $text = trim($text);
  60.   if (in_array(
  61.     $text,
  62.     array(
  63.       json_decode('"\uD83C\uDF04"') . ' Фотография',
  64.       json_decode('"\uD83D\uDCDD"') . ' Образование',
  65.       json_decode('"\uD83C\uDFA8"') . ' Творчество'
  66.     )
  67.   )) {
  68.     $data = array(
  69.       'text' => 'Выбран тэг: ' . $text,
  70.     );
  71.  
  72.     //Превращаем слово из запроса в тэги блокчейна
  73.     if ($text == json_decode('"\uD83C\uDF04"') . ' Фотография') {
  74.       $golos_tags = array('ru--fotografiya', 'ru--foto', 'ru--fotografii', 'ru--fotogolosishche');
  75.     }
  76.     if ($text == json_decode('"\uD83D\uDCDD"') . ' Образование') {
  77.       $golos_tags = array('ru--obrazovanie', 'ru--nauka', 'ru--sovety');
  78.     }
  79.     if ($text == json_decode('"\uD83C\uDFA8"') . ' Творчество') {
  80.       $golos_tags = array('ru--stikhi', 'ru--muzyka', 'ru--knigi', 'ru--tvorchestvo');
  81.     }
  82.  
  83.     //подгружаем библиотеку для подключения к блокчейну
  84.     require('vendor/autoload.php');
  85.     $client = new WebSocket\Client("wss://ws.golos.io/");
  86.  
  87.     //массив для материалов
  88.     $links = array();
  89.     foreach ($golos_tags as $golos_tag) {
  90.       //перебираем все тэги группы тэгов
  91.       $req = json_encode(
  92.         [
  93.           'id' => 1, 'method' => 'get_discussions_by_created', 'params' =>
  94.           [
  95.             [
  96.               'tag' => $golos_tag,
  97.               'limit' => 10,
  98.  
  99.             ]
  100.           ]
  101.         ]
  102.       );
  103.       $client->send($req);
  104.       $golos_resp = $client->receive();
  105.       $resp_object = json_decode($golos_resp);
  106.       if (!empty($resp_object->result)) {
  107.         foreach ($resp_object->result as $post) {
  108.           //ключем элементов массива будет id поста. Он уникален, поэтому не будет дублей
  109.           $links[$post->id] = array(
  110.             'title' => $post->title,
  111.             'url' => 'https://golos.io' . $post->url,
  112.             'created' => $post->created,
  113.           );
  114.         }
  115.       }
  116.     }
  117.     //сортируем массив по дате
  118.     usort($links, function($a, $b){if ($a['created'] == $b['created']) return 0;return $a['created'] > $b['created'] ? -1 : 1;});
  119.  
  120.     //обрезаем первые 10 элементов
  121.     $links = array_slice($links, 0, 10);
  122.  
  123.     //превращаем массивы в строки
  124.     $links_strings = array();
  125.     foreach ($links as $link) {
  126.       $links_strings[] = '<a href="' . $link['url'] . '">' . $link['title'] . '</a>';
  127.     }
  128.  
  129.  
  130.     $data['text'] = implode("\n", $links_strings);
  131.     $data['parse_mode'] = 'HTML';
  132.     $data['disable_web_page_preview'] = true;
  133.  
  134.     return $data;
  135.   }
  136.   return NULL;
  137. }
  138.  
  139. //проверка на приветствие
  140. function commIsHello($text) {
  141.   $hello = array();
  142.   $hello[] = 'привет';
  143.   $hello[] = 'хай';
  144.   $hello[] = 'здорова';
  145.   $hello[] = 'здравствуйте';
  146.   $hello[] = 'здрасьте';
  147.   $hello[] = 'йо';
  148.  
  149.   $bot_hello = array();
  150.   $bot_hello[] = 'И тебе привет';
  151.   $bot_hello[] = 'Привет от голоса';
  152.   $bot_hello[] = 'Доброго времени суток';
  153.   $bot_hello[] = 'Привет привет';
  154.  
  155.   if (in_array(mb_strtolower($text), $hello)) {
  156.     //пользователь поздоровался.
  157.     //случайная фраза привет от бота
  158.     $bot_resp = $bot_hello[rand(0, (count($bot_hello) - 1))];
  159.     $data = array(
  160.       'text' => $bot_resp,
  161.     );
  162.     return $data;
  163.   }
  164.   return NULL;
  165. }
  166.  
  167. //проверка на ник
  168. function commIsUser($text) {
  169.   $text = trim($text);//обрезаем пробелы в начале и в конце
  170.   $space = strpos($text, ' ');
  171.   if (($space === FALSE) && (mb_substr($text, 0, 1) == '@')) {
  172.     //возможно это ник пользователя
  173.     //подключаемся к блокчейну
  174.     require('vendor/autoload.php');
  175.     $client = new WebSocket\Client("wss://ws.golos.io/");
  176.     $req = json_encode(
  177.       [
  178.         'id' => 1, 'method' => 'get_accounts', 'params' => [[mb_substr($text, 1)]]
  179.       ]
  180.     );
  181.     $client->send($req);
  182.     $golos_resp = $client->receive();
  183.     $resp_object = json_decode($golos_resp);
  184.     if (!empty($resp_object->result)) {
  185.       $obj = $resp_object->result[0];
  186.       $user = array();
  187.       $user[] = 'ID: ' . $obj->id;
  188.       $user[] = 'Логин: ' . $obj->name;
  189.       $user[] = 'Аккаунт создан: ' . $obj->created;
  190.       $user[] = 'Последний раз голосовал: ' . $obj->last_vote_time;
  191.       $user[] = 'Голосов: ' . $obj->balance;
  192.       $user[] = 'Золота: ' . $obj->sbd_balance;
  193.       $user[] = 'Создано постов: ' . $obj->post_count;
  194.  
  195.       //расчёт репутации
  196.       $reputation = $obj->reputation;
  197.       $user[] = 'Репутация: ' . round((max(log10(abs($reputation)) - 9,0) * (($reputation >= 0) ? 1 : -1) * 9 + 25), 3);
  198.  
  199.       $json_metadata = json_decode($obj->json_metadata);
  200.       if (!empty($json_metadata->user_image)) {
  201.         //фото
  202.         // передавать не буду, так как у некоторых логинов "заколдованные" аватары и сообщение в телеграм не приходит
  203.        // $user[] = 'Аватар: ' . $json_metadata->user_image;
  204.       }
  205.       $text = implode("\n", $user);
  206.  
  207.       $data = array(
  208.         'text' => $text,
  209.         'parse_mode' => 'Markdown',
  210.       );
  211.     }
  212.     else {
  213.       $data = array(
  214.         'text' => 'Пользователь не найден.',
  215.       );
  216.     }
  217.     $client->close();
  218.  
  219.     if (!empty($data)) {
  220.       return $data;
  221.     }
  222.   }
  223.   return NULL;
  224. }
  225.  
  226. //отправка запроса в чат
  227. function requestToTelegram($data, $type = 'sendMessage') {
  228.   if( $curl = curl_init() ) {
  229.     curl_setopt($curl, CURLOPT_URL, API_URL . $type);
  230.     curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
  231.     curl_setopt($curl, CURLOPT_POST, TRUE);
  232.     curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
  233.     curl_exec($curl);
  234.     curl_close($curl);
  235.   }
  236. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement