/
vr5
/
monobot
Обзор
Документация
Войти
/
vr5
/
monobot
Код
Запросы
0
Пакеты
0
Релизы
0
Аналитика
Безопасность
master
app/Http/Controllers/ApiController.php
397 строк
11 KB
Alexander Volosenkov
исправлена ошибка с отсутствием las_name
06 сен 2018, 16:53
06 сен 2018, 16:53
922ee5e
Код
Авторство
О чём код?
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use Illuminate\Support\Facades\DB; use Telegram\Bot\Api; use Telegram; use Log; use Illuminate\Database\Eloquent\ModelNotFoundException; use Telegram\Bot\Commands\Command; use Telegram\Bot\Keyboard\Keyboard; use DialogFlow\Client as DialogFlowClient; //models use App\Models\QuestionsModel as Question; use App\Models\AnswersModel as Answer; use App\Models\StatisticsModel as Statistics; class ApiController extends Controller { private $webhookurl; // emoji https://apps.timwhitlock.info/emoji/tables/unicode private $correct_answers = [ 'Поздравляю! Вы дали верный ответ!' . "\xF0\x9F\x91\x8D", "\xF0\x9F\x8E\x89" . ' СОВЕРШЕННО ВЕРНО!! ' . "\xF0\x9F\x8E\x89", "\xE2\x80\xBC" . ' И это совершенно правильный ответ!! ' . "\xE2\x80\xBC" ]; private $incorrect_answers = [ "\xF0\x9F\x91\x8E" . ' К сожалению Вы ошиблись ' . "\xF0\x9F\x91\x8E", "\xF0\x9F\x91\x8E" . ' Это не верно ' . "\xF0\x9F\x91\x8E", "\xF0\x9F\x91\x8E" . ' Это не верный ответ ' . "\xF0\x9F\x91\x8E", "\xF0\x9F\x91\x8E" . ' Ошибочка вышла ' . "\xF0\x9F\x91\x8E", "\xF0\x9F\x91\x8E" . ' Нет, это не верно ' . "\xF0\x9F\x91\x8E" ]; /** * Constructor * * * * */ public function __construct() { //set webhook url $this->webhookurl = env( 'TELEGRAM_BOT_WEBHOOK_URL' ) . env( 'TELEGRAM_BOT_TOKEN' ) . '/webhook'; } /** * * * * * */ public function me(){ $response = Telegram::getMe(); return $response; } /** * Set webhook url for telegram bot * * * */ public function setwebhook() { $telegram = new Api( env( 'TELEGRAM-BOT-TOKEN' ) ); $response = $telegram->setWebhook( ['url' => $this->webhookurl ] ); var_dump( $response ); } /** * * * * * */ public function removewebhook() { $telegram = new Api( env( 'TELEGRAM-BOT-TOKEN' ) ); $telegram->removeWebHook( [ 'url' => $this->webhookurl ] ); } /** * Webhook * * * * */ public function webhook( Request $request ) { Log::alert( $request ); //Proccess inline keyboard callback query if( $request['callback_query'] != null ) { $this->processStatistics( $request['callback_query'] ); //callback data //$data[0] - question id //$data[1] - answer id //$data[2] - is_correct $data = unserialize ( $request['callback_query']['data'] ); //$message = $request['callback_query']['message']; //user id $user_id = $request['callback_query']['from']['id']; //callback query id $callback_query_id = $request['callback_query']['id']; //chat id $chat_id = $request['callback_query']['message']['chat']['id']; //message id $message_id = $request['callback_query']['message']['message_id']; Telegram::answerCallbackQuery([ 'callback_query_id' => $callback_query_id ]); //$data[0] - question id //$data[1] - answer id //$data[2] - is_correct // question text $question_txt = htmlspecialchars_decode( Question::find( $data[0] )->text ); // user answer text $answer_txt = htmlspecialchars_decode( Answer::find( $data[1] )->text ); // choose random answer $r1 = rand( 0, count( $this->correct_answers ) - 1 ); $r2 = rand( 0, count( $this->incorrect_answers ) - 1 ); // choose text for correct or incorect answer $correct_or_not = ( $data[2] == 0 ) ? $this->incorrect_answers[$r2] : $this->correct_answers[$r1]; $answer = $question_txt . chr(10) . chr(10); $answer .= '*' . $answer_txt . '*' . chr(10) . chr(10); $answer .= $correct_or_not; // if user's answer is incorrect, then choose correct answer if( $data[2] == 0 ) { $correct_answer = Question::find( $data[0] )->answer->text; $answer .= chr(10) . chr(10) . 'Правильный ответ: *' . $correct_answer . '*'; } Telegram::editMessageText([ 'chat_id' => $chat_id, 'message_id' => $message_id, 'parse_mode' => 'markdown', 'text' => $answer ]); } //proccess user messages if( $request['message'] != null ) { $chatid = $request['message']['chat']['id']; $text = $request['message']['text']; $user_id = $request['message']['from']['id']; switch( $text ) { case '/start': $text = 'Привет! Как твои дела?' . chr(10); $text .= 'Я Мозгобот. Я могу поиграть с тобой в вопросы/ответы.' . chr(10); $text .= 'Набери команду /ask и попробуй правильно ответить на мой вопрос.' . chr(10); $text .= 'Набери /stat чтобы увидеть свою статистику.' . chr(10); $response = Telegram::setAsyncRequest(true)->sendMessage([ 'chat_id' => $chatid, 'text' => $text ]); $this->createStatistics( $request['message'] ); break; case '/menu': $response = Telegram::setAsyncRequest(true)->sendMessage([ 'chat_id' => $chatid, 'text' => "hello" ]); break; case '/ask': $this->doAsk( $chatid ); break; case '/stat': $msg = 'СТАТИСТИКА БОТА:' . chr(10); $msg .= 'количество вопросов в базе: ' . Question::count() . chr(10); $msg .= 'количество пользователей: ' . Statistics::count() . chr(10) . chr(10); $msg .= 'ЛИЧНАЯ СТАТИСТИКА:' . chr(10); $msg .= 'вопросов задано: ' . Statistics::where('user_id', $user_id )->first()->q_cnt . chr(10); $msg .= 'правильных ответов: ' . Statistics::where('user_id', $user_id )->first()->correct_cnt . chr(10); $msg .= 'неправильных ответов: ' . Statistics::where('user_id', $user_id )->first()->incorrect_cnt . chr(10); $response = Telegram::setAsyncRequest(true)->sendMessage([ 'chat_id' => $chatid, 'text' => $msg ]); break; case '/help' : $this->doHelp( $chatid ); break; default: $this->doAnswer( $text, $chatid ); } } return; } /** * Ask question to user * * * * */ private function doAsk( $chatid ) { // get random question from database $question = Question::all()->random(1)[0]; // get answers to question $answers = $question->answers; // randomize answers $rnd = [0,1,2,3]; srand( (float)microtime() * 1000000 ); shuffle( $rnd ); // create keyboard markup with 4 answers $keyboard = Keyboard::make() ->inline() ->row( Keyboard::inlineButton( ['text' => htmlspecialchars_decode( $answers[$rnd[0]]->text ), 'callback_data' => serialize([$question->id, $answers[$rnd[0]]->id, $answers[$rnd[0]]->is_correct]) ] ) ) ->row( Keyboard::inlineButton( ['text' => htmlspecialchars_decode( $answers[$rnd[1]]->text ), 'callback_data' => serialize([$question->id, $answers[$rnd[1]]->id, $answers[$rnd[1]]->is_correct]) ] ) ) ->row( Keyboard::inlineButton( ['text' => htmlspecialchars_decode( $answers[$rnd[2]]->text ), 'callback_data' => serialize([$question->id, $answers[$rnd[2]]->id, $answers[$rnd[2]]->is_correct]) ] ) ) ->row( Keyboard::inlineButton( ['text' => htmlspecialchars_decode( $answers[$rnd[3]]->text ), 'callback_data' => serialize([$question->id, $answers[$rnd[3]]->id, $answers[$rnd[3]]->is_correct]) ] ) ); // send message to user Telegram::sendMessage( [ 'chat_id' => $chatid, 'text' => '*' . htmlspecialchars_decode( $question['text'] ) . '*', 'parse_mode' => 'markdown', 'reply_markup' => $keyboard] ); } /** * answer to user through DialogFlow * * * * */ private function doAnswer( $question, $chatid ) { try { $client = new DialogFlowClient( env( 'DIALOGFLOW_TOKEN' ) ); $query = $client->get( 'query', [ 'query' => $question, 'sessionId' => 'monobot', 'lang' => 'ru' ] ); $response = json_decode((string) $query->getBody(), true); if( $response['status']['code'] == 200 ) { Telegram::sendMessage([ 'chat_id' => $chatid, 'text' => (string)$response['result']['fulfillment']['speech'] ]); } else Log::error( $response['status']['errorType'] ); } catch ( \Exception $error ) { Log::error( $error->getMessage() ); } } /** * * display bot statistics * * * */ private function processStatistics( $callback_query ) { //user id $user_id = (int)$callback_query['from']['id']; $data = unserialize ( $callback_query['data'] ); $this->createStatistics( $callback_query ); Statistics::where( 'user_id', $user_id )->increment( 'q_cnt' ); if ( $data[2] == 0 ) Statistics::where( 'user_id', $user_id )->increment( 'incorrect_cnt' ); if( $data[2] == 1 ) Statistics::where( 'user_id', $user_id )->increment( 'correct_cnt' ); } /** * * * * * */ private function doHelp( $chatid ) { $msg = 'СПИСОК КОМАНД:' . chr(10); $msg .= '/help - получить справку' . chr(10); $msg .= '/ask - бот задает вопрос, Вы отвечаете' . chr(10); $msg .= '/stat - Ваша персональная статистика' . chr(10); $response = Telegram::setAsyncRequest(true)->sendMessage([ 'chat_id' => $chatid, 'text' => $msg ]); } /** * add user and statistic to database * * * */ private function createStatistics( $message ) { //user id $user_id = (int)$message['from']['id']; try { $stat = Statistics::where( 'user_id', $user_id )->firstOrFail(); } catch( ModelNotFoundException $e ) { $stat = new Statistics(); $stat->user_id = $user_id; $stat->first_name = $message['from']['first_name']; if( $message['from']['last_name'] != null ) $stat->last_name = $message['from']['last_name']; else $stat->last_name = ''; $stat->save(); } } }