Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- //запись в лог
- function teleToLog($log) {
- $myFile = 'log.txt';
- $fh = fopen($myFile, 'a') or die('can\'t open file');
- if ((is_array($log)) || (is_object($log))) {
- $updateArray = print_r($log, TRUE);
- fwrite($fh, $updateArray."\n");
- } else {
- fwrite($fh, $log . "\n");
- }
- fclose($fh);
- }
- //обработка запроса от пользователя
- function getUserRequest($text, $chat_id) {
- $resp = [];
- $resp['chat_id'] = $chat_id;
- $resp['text'] = 'Приветствую вас';
- $menu = array(
- 'keyboard' => array(
- array(
- array('text' => json_decode('"\uD83C\uDF04"') . ' Фотография')
- ),
- array(
- array('text' => json_decode('"\uD83D\uDCDD"') . ' Образование')
- ),
- array(
- array('text' => json_decode('"\uD83C\uDFA8"') . ' Творчество')
- ),
- )
- );
- $resp['reply_markup'] = json_encode($menu);
- $data = commIsHello($text);
- if (!empty($data)) {
- $resp = array_merge($resp, $data);
- requestToTelegram($resp);
- return TRUE;
- }
- $data = commIsUser($text);
- if (!empty($data)) {
- $resp = array_merge($resp, $data);
- requestToTelegram($resp);
- return TRUE;
- }
- $data = commIsTag($text);
- if (!empty($data)) {
- $resp = array_merge($resp, $data);
- requestToTelegram($resp);
- return TRUE;
- }
- requestToTelegram($resp);
- }
- //проверка на тэг
- function commIsTag($text) {
- $text = trim($text);
- if (in_array(
- $text,
- array(
- json_decode('"\uD83C\uDF04"') . ' Фотография',
- json_decode('"\uD83D\uDCDD"') . ' Образование',
- json_decode('"\uD83C\uDFA8"') . ' Творчество'
- )
- )) {
- $data = array(
- 'text' => 'Выбран тэг: ' . $text,
- );
- //Превращаем слово из запроса в тэги блокчейна
- if ($text == json_decode('"\uD83C\uDF04"') . ' Фотография') {
- $golos_tags = array('ru--fotografiya', 'ru--foto', 'ru--fotografii', 'ru--fotogolosishche');
- }
- if ($text == json_decode('"\uD83D\uDCDD"') . ' Образование') {
- $golos_tags = array('ru--obrazovanie', 'ru--nauka', 'ru--sovety');
- }
- if ($text == json_decode('"\uD83C\uDFA8"') . ' Творчество') {
- $golos_tags = array('ru--stikhi', 'ru--muzyka', 'ru--knigi', 'ru--tvorchestvo');
- }
- //подгружаем библиотеку для подключения к блокчейну
- require('vendor/autoload.php');
- $client = new WebSocket\Client("wss://ws.golos.io/");
- //массив для материалов
- $links = array();
- foreach ($golos_tags as $golos_tag) {
- //перебираем все тэги группы тэгов
- $req = json_encode(
- [
- 'id' => 1, 'method' => 'get_discussions_by_created', 'params' =>
- [
- [
- 'tag' => $golos_tag,
- 'limit' => 10,
- ]
- ]
- ]
- );
- $client->send($req);
- $golos_resp = $client->receive();
- $resp_object = json_decode($golos_resp);
- if (!empty($resp_object->result)) {
- foreach ($resp_object->result as $post) {
- //ключем элементов массива будет id поста. Он уникален, поэтому не будет дублей
- $links[$post->id] = array(
- 'title' => $post->title,
- 'url' => 'https://golos.io' . $post->url,
- 'created' => $post->created,
- );
- }
- }
- }
- //сортируем массив по дате
- usort($links, function($a, $b){if ($a['created'] == $b['created']) return 0;return $a['created'] > $b['created'] ? -1 : 1;});
- //обрезаем первые 10 элементов
- $links = array_slice($links, 0, 10);
- //превращаем массивы в строки
- $links_strings = array();
- foreach ($links as $link) {
- $links_strings[] = '<a href="' . $link['url'] . '">' . $link['title'] . '</a>';
- }
- $data['text'] = implode("\n", $links_strings);
- $data['parse_mode'] = 'HTML';
- $data['disable_web_page_preview'] = true;
- return $data;
- }
- return NULL;
- }
- //проверка на приветствие
- function commIsHello($text) {
- $hello = array();
- $hello[] = 'привет';
- $hello[] = 'хай';
- $hello[] = 'здорова';
- $hello[] = 'здравствуйте';
- $hello[] = 'здрасьте';
- $hello[] = 'йо';
- $bot_hello = array();
- $bot_hello[] = 'И тебе привет';
- $bot_hello[] = 'Привет от голоса';
- $bot_hello[] = 'Доброго времени суток';
- $bot_hello[] = 'Привет привет';
- if (in_array(mb_strtolower($text), $hello)) {
- //пользователь поздоровался.
- //случайная фраза привет от бота
- $bot_resp = $bot_hello[rand(0, (count($bot_hello) - 1))];
- $data = array(
- 'text' => $bot_resp,
- );
- return $data;
- }
- return NULL;
- }
- //проверка на ник
- function commIsUser($text) {
- $text = trim($text);//обрезаем пробелы в начале и в конце
- $space = strpos($text, ' ');
- if (($space === FALSE) && (mb_substr($text, 0, 1) == '@')) {
- //возможно это ник пользователя
- //подключаемся к блокчейну
- require('vendor/autoload.php');
- $client = new WebSocket\Client("wss://ws.golos.io/");
- $req = json_encode(
- [
- 'id' => 1, 'method' => 'get_accounts', 'params' => [[mb_substr($text, 1)]]
- ]
- );
- $client->send($req);
- $golos_resp = $client->receive();
- $resp_object = json_decode($golos_resp);
- if (!empty($resp_object->result)) {
- $obj = $resp_object->result[0];
- $user = array();
- $user[] = 'ID: ' . $obj->id;
- $user[] = 'Логин: ' . $obj->name;
- $user[] = 'Аккаунт создан: ' . $obj->created;
- $user[] = 'Последний раз голосовал: ' . $obj->last_vote_time;
- $user[] = 'Голосов: ' . $obj->balance;
- $user[] = 'Золота: ' . $obj->sbd_balance;
- $user[] = 'Создано постов: ' . $obj->post_count;
- //расчёт репутации
- $reputation = $obj->reputation;
- $user[] = 'Репутация: ' . round((max(log10(abs($reputation)) - 9,0) * (($reputation >= 0) ? 1 : -1) * 9 + 25), 3);
- $json_metadata = json_decode($obj->json_metadata);
- if (!empty($json_metadata->user_image)) {
- //фото
- // передавать не буду, так как у некоторых логинов "заколдованные" аватары и сообщение в телеграм не приходит
- // $user[] = 'Аватар: ' . $json_metadata->user_image;
- }
- $text = implode("\n", $user);
- $data = array(
- 'text' => $text,
- 'parse_mode' => 'Markdown',
- );
- }
- else {
- $data = array(
- 'text' => 'Пользователь не найден.',
- );
- }
- $client->close();
- if (!empty($data)) {
- return $data;
- }
- }
- return NULL;
- }
- //отправка запроса в чат
- function requestToTelegram($data, $type = 'sendMessage') {
- if( $curl = curl_init() ) {
- curl_setopt($curl, CURLOPT_URL, API_URL . $type);
- curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
- curl_setopt($curl, CURLOPT_POST, TRUE);
- curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
- curl_exec($curl);
- curl_close($curl);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement