From 80ce39808e9585baba9e8582db12dfac34f3d1d1 Mon Sep 17 00:00:00 2001 From: LONGMAN Date: Mon, 6 Jul 2015 22:10:09 +0400 Subject: [PATCH] Code rewrited on PSR-2 standard. Added CONTRIBUTING.md for contributors --- CONTRIBUTING.md | 14 + README.md | 20 +- build/phpcs/ruleset.xml | 74 +-- composer.lock | 4 +- src/Command.php | 135 ++-- src/Commands/CalcCommand.php | 72 +-- src/Commands/DateCommand.php | 286 ++++----- src/Commands/EchoCommand.php | 51 +- src/Commands/HelpCommand.php | 104 ++-- src/Commands/WeatherCommand.php | 214 +++---- src/Commands/WhoamiCommand.php | 59 +- src/Entities/Chat.php | 74 +-- src/Entities/Entity.php | 39 +- src/Entities/Message.php | 246 ++++---- src/Entities/Update.php | 53 +- src/Entities/User.php | 77 ++- src/Exception/TelegramException.php | 6 +- src/Request.php | 198 +++--- src/Telegram.php | 928 ++++++++++++++-------------- 19 files changed, 1269 insertions(+), 1385 deletions(-) create mode 100644 CONTRIBUTING.md diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 000000000..89a3bab34 --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,14 @@ +Contributing +------------- + +Before you contribute code to php-telegram-bot, please make sure it conforms to the PHPCS coding standard and that the php-telegram-bot unit tests still pass. The easiest way to contribute is to work on a checkout of the repository, or your own fork, rather than an installed PEAR version. If you do this, you can run the following commands to check if everything is ready to submit: + + cd php-telegram-bot + composer update + vendor/bin/phpcs --report=full --extensions=php -p --standard=build/phpcs . + +Which should give you no output, indicating that there are no coding standard errors. And then: + + phpunit + +Which should give you no failures or errors. You can ignore any skipped tests as these are for external tools. \ No newline at end of file diff --git a/README.md b/README.md index 9fb867c8b..811e2d6b5 100644 --- a/README.md +++ b/README.md @@ -100,14 +100,14 @@ Create set.php and put: ```php setWebHook('https://yourdomain/yourpath_to_hook.php'); @@ -123,9 +123,9 @@ After create hook.php and put: ```php enableMySQL($credentials); This code is available on [Github][0]. Pull requests are welcome. + Troubleshooting ---------------- +------------- + If you like living on the edge, please report any bugs you find on the [PHP Telegram Bot issues](https://github.com/akalongman/php-telegram-bot/issues) page. +Contributing +------------- + +See [CONTRIBUTING.md](CONTRIBUTING.md) for information. + + ## Credits Created by [Avtandil Kikabidze][1]. diff --git a/build/phpcs/ruleset.xml b/build/phpcs/ruleset.xml index 0678d989a..6396bbf46 100644 --- a/build/phpcs/ruleset.xml +++ b/build/phpcs/ruleset.xml @@ -1,67 +1,25 @@ - The Package coding standard. + The Package coding standard. - - build/* - docs/* - tests/* - cache/* - tmp/* - logs/* + + build/* + docs/* + tests/* + cache/* + tmp/* + logs/* - - vendor/* + + vendor/* - + - + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 0 - + + + + diff --git a/composer.lock b/composer.lock index 5ebfc46ed..5407875a9 100644 --- a/composer.lock +++ b/composer.lock @@ -4,7 +4,7 @@ "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#composer-lock-the-lock-file", "This file is @generated automatically" ], - "hash": "02634aa637830c6e9324925abceb4624", + "hash": "e4b463e1eea6333a1eaf38457a54b29c", "packages": [ { "name": "hoa/compiler", @@ -1868,7 +1868,7 @@ "prefer-stable": false, "prefer-lowest": false, "platform": { - "php": ">=5.3.0", + "php": ">=5.4.0", "ext-pdo": "*" }, "platform-dev": [] diff --git a/src/Command.php b/src/Command.php index 8e762cfa3..5902a34ab 100644 --- a/src/Command.php +++ b/src/Command.php @@ -1,4 +1,5 @@ telegram = $telegram; - } - - public function setUpdate(Update $update) { - $this->update = $update; - $this->message = $this->update->getMessage(); - return $this; - } - - - public abstract function execute(); - - - public function getUpdate() { - return $this->update; - } - - public function getMessage() { - return $this->message; - } - - - public function getTelegram() { - return $this->telegram; - } - - public function setCommand($command) { - $this->command = $command; - return $this; - } - - public function getUsage() { - return $this->usage; - } - - public function getVersion() { - return $this->version; - } - - public function getDescription() { - return $this->description; - } - - public function getName() { - return $this->name; - } - - public function isEnabled() { - return $this->enabled; - } + protected $telegram; + protected $update; + protected $message; + protected $command; + + protected $description = 'Command help'; + protected $usage = 'Command usage'; + protected $version = '1.0.0'; + protected $enabled = true; + protected $name = ''; + + public function __construct(Telegram $telegram) + { + $this->telegram = $telegram; + } + + public function setUpdate(Update $update) + { + $this->update = $update; + $this->message = $this->update->getMessage(); + return $this; + } + + abstract public function execute(); + + public function getUpdate() + { + return $this->update; + } + + public function getMessage() + { + return $this->message; + } + + public function getTelegram() + { + return $this->telegram; + } + + public function setCommand($command) + { + $this->command = $command; + return $this; + } + + public function getUsage() + { + return $this->usage; + } + + public function getVersion() + { + return $this->version; + } + + public function getDescription() + { + return $this->description; + } + + public function getName() + { + return $this->name; + } + + public function isEnabled() + { + return $this->enabled; + } } diff --git a/src/Commands/CalcCommand.php b/src/Commands/CalcCommand.php index 79afe492b..60865d0d6 100644 --- a/src/Commands/CalcCommand.php +++ b/src/Commands/CalcCommand.php @@ -1,4 +1,5 @@ - */ +*/ namespace Longman\TelegramBot\Commands; use Longman\TelegramBot\Request; @@ -17,52 +18,45 @@ class CalcCommand extends Command { - protected $name = 'calc'; - protected $description = 'Calculate math expression'; - protected $usage = '/calc '; - protected $version = '1.0.0'; - protected $enabled = true; - - - public function execute() { - $update = $this->getUpdate(); - $message = $this->getMessage(); - + protected $name = 'calc'; + protected $description = 'Calculate math expression'; + protected $usage = '/calc '; + protected $version = '1.0.0'; + protected $enabled = true; - $chat_id = $message->getChat()->getId(); - $message_id = $message->getMessageId(); - $text = $message->getText(true); + public function execute() + { + $update = $this->getUpdate(); + $message = $this->getMessage(); + $chat_id = $message->getChat()->getId(); + $message_id = $message->getMessageId(); + $text = $message->getText(true); - $data = array(); - $data['chat_id'] = $chat_id; - $data['reply_to_message_id'] = $message_id; - $data['text'] = $this->compute($text); + $data = array(); + $data['chat_id'] = $chat_id; + $data['reply_to_message_id'] = $message_id; + $data['text'] = $this->compute($text); - $result = Request::sendMessage($data); - return $result; - } + $result = Request::sendMessage($data); + return $result; + } + protected function compute($expression) + { - protected function compute($expression) { + // Load the compiler + $compiler = \Hoa\Compiler\Llk::load(new \Hoa\File\Read('hoa://Library/Math/Arithmetic.pp')); - // Load the compiler - $compiler = \Hoa\Compiler\Llk::load( - new \Hoa\File\Read('hoa://Library/Math/Arithmetic.pp') - ); + // Load the visitor, aka the "evaluator" + $visitor = new \Hoa\Math\Visitor\Arithmetic(); - // Load the visitor, aka the "evaluator" - $visitor = new \Hoa\Math\Visitor\Arithmetic(); - - // Parse the expression - $ast = $compiler->parse($expression); - - // Evaluate - $result = $visitor->visit($ast); - - return $result; - } + // Parse the expression + $ast = $compiler->parse($expression); + // Evaluate + $result = $visitor->visit($ast); + return $result; + } } - diff --git a/src/Commands/DateCommand.php b/src/Commands/DateCommand.php index 987aaf2d2..9eb794f90 100644 --- a/src/Commands/DateCommand.php +++ b/src/Commands/DateCommand.php @@ -1,4 +1,5 @@ '; - protected $version = '1.0.0'; - protected $enabled = true; - - - private $google_api_key = ''; - private $base_url = 'https://maps.googleapis.com/maps/api'; - private $date_format = 'd-m-Y H:i:s'; - - - - - - - private function getCoordinates($location) { - $url = $this->base_url.'/geocode/json?'; - $params = 'address='.urlencode($location); - if (!empty($this->google_api_key)) { - $params .= '&key='.$this->google_api_key; - } - - $data = $this->request($url.$params); - if (empty($data)) { - return false; - } - - $data = json_decode($data, true); - if (empty($data)) { - return false; - } - - if ($data['status'] !== 'OK') { - return false; - } - - $lat = $data['results'][0]['geometry']['location']['lat']; - $lng = $data['results'][0]['geometry']['location']['lng']; - $acc = $data['results'][0]['geometry']['location_type']; - $types = $data['results'][0]['types']; - - return array($lat, $lng, $acc, $types); - } - - - - private function getDate($lat, $lng) { - $url = $this->base_url.'/timezone/json?'; - - - $timestamp = time(); - - - $params = 'location='.urlencode($lat).','.urlencode($lng).'×tamp='.urlencode($timestamp); - if (!empty($this->google_api_key)) { - $params .= '&key='.$this->google_api_key; - } - - $data = $this->request($url.$params); - if (empty($data)) { - return false; - } - - $data = json_decode($data, true); - if (empty($data)) { - return false; - } - - if ($data['status'] !== 'OK') { - return false; - } - - - $local_time = $timestamp + $data['rawOffset'] + $data['dstOffset']; - - return array($local_time, $data['timeZoneId']); - } - - private function getFormattedDate($location) { - if (empty($location)) { - return 'The time in nowhere is never'; - } - list($lat, $lng, $acc, $types) = $this->getCoordinates($location); - - if (empty($lat) || empty($lng)) { - return 'It seems that in "'.$location.'" they do not have a concept of time.'; - } - - list($local_time, $timezone_id) = $this->getDate($lat, $lng); - - - - $date_utc = new \DateTime(date('Y-m-d H:i:s', $local_time), new \DateTimeZone($timezone_id)); - //$timestamp = $date_utc->format($this->date_format); - - $return = 'The local time in '.$timezone_id.' is: '.date($this->date_format, $local_time).''; - - return $return; - } - - - private function request($url) { - $ch = curl_init(); - $curlConfig = array( - CURLOPT_URL => $url, - CURLOPT_RETURNTRANSFER => true, - ); - - curl_setopt_array($ch, $curlConfig); - $response = curl_exec($ch); - - $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE); - if ($http_code !== 200) { - throw new \Exception('Error receiving data from url'); - } - curl_close($ch); - - return $response; - } - - - public function execute() { - $update = $this->getUpdate(); - $message = $this->getMessage(); - - - - $chat_id = $message->getChat()->getId(); - $message_id = $message->getMessageId(); - $text = $message->getText(true); - - - - if (empty($text)) { - $text = 'You must specify location in format: /date '; - } else { - $date = $this->getformattedDate($text); - if (empty($date)) { - $text = 'Can not find date for location: '.$text; - } else { - $text = $date; - } - } - + protected $name = 'date'; + protected $description = 'Show date/time by location'; + protected $usage = '/date '; + protected $version = '1.0.0'; + protected $enabled = true; - $data = array(); - $data['chat_id'] = $chat_id; - $data['reply_to_message_id'] = $message_id; - $data['text'] = $text; + private $google_api_key = ''; + private $base_url = 'https://maps.googleapis.com/maps/api'; + private $date_format = 'd-m-Y H:i:s'; + private function getCoordinates($location) + { + $url = $this->base_url . '/geocode/json?'; + $params = 'address=' . urlencode($location); + if (!empty($this->google_api_key)) { + $params.= '&key=' . $this->google_api_key; + } - $result = Request::sendMessage($data); - } + $data = $this->request($url . $params); + if (empty($data)) { + return false; + } + + $data = json_decode($data, true); + if (empty($data)) { + return false; + } + + if ($data['status'] !== 'OK') { + return false; + } + + $lat = $data['results'][0]['geometry']['location']['lat']; + $lng = $data['results'][0]['geometry']['location']['lng']; + $acc = $data['results'][0]['geometry']['location_type']; + $types = $data['results'][0]['types']; + + return array($lat, $lng, $acc, $types); + } + + private function getDate($lat, $lng) + { + $url = $this->base_url . '/timezone/json?'; + + $timestamp = time(); + + $params = 'location=' . urlencode($lat) . ',' . urlencode($lng) . '×tamp=' . urlencode($timestamp); + if (!empty($this->google_api_key)) { + $params.= '&key=' . $this->google_api_key; + } + + $data = $this->request($url . $params); + if (empty($data)) { + return false; + } + + $data = json_decode($data, true); + if (empty($data)) { + return false; + } + + if ($data['status'] !== 'OK') { + return false; + } + + $local_time = $timestamp + $data['rawOffset'] + $data['dstOffset']; + + return array($local_time, $data['timeZoneId']); + } + + private function getFormattedDate($location) + { + if (empty($location)) { + return 'The time in nowhere is never'; + } + list($lat, $lng, $acc, $types) = $this->getCoordinates($location); + + if (empty($lat) || empty($lng)) { + return 'It seems that in "' . $location . '" they do not have a concept of time.'; + } + + list($local_time, $timezone_id) = $this->getDate($lat, $lng); + + $date_utc = new \DateTime(date('Y-m-d H:i:s', $local_time), new \DateTimeZone($timezone_id)); + + //$timestamp = $date_utc->format($this->date_format); + + $return = 'The local time in ' . $timezone_id . ' is: ' . date($this->date_format, $local_time) . ''; + + return $return; + } + + private function request($url) + { + $ch = curl_init(); + $curlConfig = array(CURLOPT_URL => $url, CURLOPT_RETURNTRANSFER => true,); + + curl_setopt_array($ch, $curlConfig); + $response = curl_exec($ch); + + $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE); + if ($http_code !== 200) { + throw new TelegramException('Error receiving data from url'); + } + curl_close($ch); + + return $response; + } + + public function execute() + { + $update = $this->getUpdate(); + $message = $this->getMessage(); + + $chat_id = $message->getChat()->getId(); + $message_id = $message->getMessageId(); + $text = $message->getText(true); + if (empty($text)) { + $text = 'You must specify location in format: /date '; + } else { + $date = $this->getformattedDate($text); + if (empty($date)) { + $text = 'Can not find date for location: ' . $text; + } else { + $text = $date; + } + } + + $data = array(); + $data['chat_id'] = $chat_id; + $data['reply_to_message_id'] = $message_id; + $data['text'] = $text; + $result = Request::sendMessage($data); + } } diff --git a/src/Commands/EchoCommand.php b/src/Commands/EchoCommand.php index 996ababf8..c3b805990 100644 --- a/src/Commands/EchoCommand.php +++ b/src/Commands/EchoCommand.php @@ -1,4 +1,5 @@ '; - protected $version = '1.0.0'; - protected $enabled = true; - - public function execute() { - $update = $this->getUpdate(); - $message = $this->getMessage(); - - - - $chat_id = $message->getChat()->getId(); - $text = $message->getText(true); - - - $data = array(); - $data['chat_id'] = $chat_id; - $data['text'] = $text; - - - $result = Request::sendMessage($data); - return $result; - } - - + protected $name = 'echo'; + protected $description = 'Show text'; + protected $usage = '/echo '; + protected $version = '1.0.0'; + protected $enabled = true; + + public function execute() + { + $update = $this->getUpdate(); + $message = $this->getMessage(); + + $chat_id = $message->getChat()->getId(); + $text = $message->getText(true); + + $data = array(); + $data['chat_id'] = $chat_id; + $data['text'] = $text; + + $result = Request::sendMessage($data); + return $result; + } } - diff --git a/src/Commands/HelpCommand.php b/src/Commands/HelpCommand.php index eb22c6a6b..25c73c05c 100644 --- a/src/Commands/HelpCommand.php +++ b/src/Commands/HelpCommand.php @@ -1,4 +1,5 @@ '; - protected $version = '1.0.0'; - protected $enabled = true; - - - public function execute() { - $update = $this->getUpdate(); - $message = $this->getMessage(); - - - - $chat_id = $message->getChat()->getId(); - $message_id = $message->getMessageId(); - $text = $message->getText(true); - - $commands = $this->telegram->getCommandsList(); - if (empty($text)) { - $msg = 'GeoBot v. '.$this->telegram->getVersion()."\n\n"; - $msg .= 'Commands List:'."\n"; - foreach($commands as $command) { - if (!$command->isEnabled()) { - continue; - } - $msg .= '/'.$command->getName().' - '.$command->getDescription()."\n"; - } - - $msg .= "\n".'For exact command help type: /help '; - } else { - $text = str_replace('/', '', $text); - if (isset($commands[$text])) { - $command = $commands[$text]; - $msg = 'Command: '.$command->getName().' v'.$command->getVersion()."\n"; - $msg .= 'Description: '.$command->getDescription()."\n"; - $msg .= 'Usage: '.$command->getUsage(); - } else { - $msg = 'Command '.$text.' not found'; - } - } - - - $data = array(); - $data['chat_id'] = $chat_id; - $data['reply_to_message_id'] = $message_id; - $data['text'] = $msg; - - - $result = Request::sendMessage($data); - return $result; - } - - + protected $name = 'help'; + protected $description = 'Show bot commands help'; + protected $usage = '/help or /help '; + protected $version = '1.0.0'; + protected $enabled = true; + + public function execute() + { + $update = $this->getUpdate(); + $message = $this->getMessage(); + + $chat_id = $message->getChat()->getId(); + $message_id = $message->getMessageId(); + $text = $message->getText(true); + + $commands = $this->telegram->getCommandsList(); + if (empty($text)) { + $msg = 'GeoBot v. ' . $this->telegram->getVersion() . "\n\n"; + $msg.= 'Commands List:' . "\n"; + foreach ($commands as $command) { + if (!$command->isEnabled()) { + continue; + } + $msg.= '/' . $command->getName() . ' - ' . $command->getDescription() . "\n"; + } + + $msg.= "\n" . 'For exact command help type: /help '; + } else { + $text = str_replace('/', '', $text); + if (isset($commands[$text])) { + $command = $commands[$text]; + $msg = 'Command: ' . $command->getName() . ' v' . $command->getVersion() . "\n"; + $msg.= 'Description: ' . $command->getDescription() . "\n"; + $msg.= 'Usage: ' . $command->getUsage(); + } else { + $msg = 'Command ' . $text . ' not found'; + } + } + + $data = array(); + $data['chat_id'] = $chat_id; + $data['reply_to_message_id'] = $message_id; + $data['text'] = $msg; + + $result = Request::sendMessage($data); + return $result; + } } - diff --git a/src/Commands/WeatherCommand.php b/src/Commands/WeatherCommand.php index b696737c5..425ac62ef 100644 --- a/src/Commands/WeatherCommand.php +++ b/src/Commands/WeatherCommand.php @@ -1,4 +1,5 @@ '; - protected $version = '1.0.0'; - protected $enabled = true; - - - private function getWeather($location) { - $url = 'http://api.openweathermap.org/data/2.5/weather?q='.$location.'&units=metric'; - - - $ch = curl_init(); - $curlConfig = array( - CURLOPT_URL => $url, - //CURLOPT_POST => true, - CURLOPT_RETURNTRANSFER => true, - //CURLOPT_HTTPHEADER => array('Content-Type: text/plain'), - //CURLOPT_POSTFIELDS => $data - //CURLOPT_VERBOSE => true, - //CURLOPT_HEADER => true, - ); - - curl_setopt_array($ch, $curlConfig); - $response = curl_exec($ch); - - $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE); - if ($http_code !== 200) { - throw new \Exception('Error receiving data from url'); - } - curl_close($ch); - - - - return $response; - } - - - private function getWeatherString($location) { - if (empty($location)) { - return false; - } - - // try/catch - $data = $this->getWeather($location); - - $decode = json_decode($data, true); - if (empty($decode) || $decode['cod'] != 200) { - return false; - } - $city = $decode['name']; - $country = $decode['sys']['country']; - $temp = 'The temperature in '.$city .' (' .$country.') is '.$decode['main']['temp'].'°C'; - $conditions = 'Current conditions are: '.$decode['weather'][0]['description']; - - switch(strtolower($decode['weather'][0]['main'])) { - case 'clear': - $conditions .= ' ☀'; - break; - - case 'clouds': - $conditions .= ' ☁☁'; - break; - - case 'rain': - $conditions .= ' ☔'; - break; - - case 'thunderstorm': - $conditions .= ' ☔☔☔☔'; - break; - } - - - return $temp."\n".$conditions; - } - - public function execute() { - $update = $this->getUpdate(); - $message = $this->getMessage(); - - - - $chat_id = $message->getChat()->getId(); - $message_id = $message->getMessageId(); - $text = $message->getText(true); - - - if (empty($text)) { - $text = 'You must specify location in format: /weather '; - } else { - $weather = $this->getWeatherString($text); - if (empty($weather)) { - $text = 'Can not find weather for location: '.$text; - } else { - $text = $weather; - } - } - - - $data = array(); - $data['chat_id'] = $chat_id; - $data['reply_to_message_id'] = $message_id; - $data['text'] = $text; - - - $result = Request::sendMessage($data); - return $result; - } - - + protected $name = 'weather'; + protected $description = 'Show weather by location'; + protected $usage = '/weather '; + protected $version = '1.0.0'; + protected $enabled = true; + + private function getWeather($location) + { + $url = 'http://api.openweathermap.org/data/2.5/weather?q=' . $location . '&units=metric'; + + $ch = curl_init(); + $curlConfig = array(CURLOPT_URL => $url, + + //CURLOPT_POST => true, + CURLOPT_RETURNTRANSFER => true, + + //CURLOPT_HTTPHEADER => array('Content-Type: text/plain'), + //CURLOPT_POSTFIELDS => $data + //CURLOPT_VERBOSE => true, + //CURLOPT_HEADER => true, + ); + + curl_setopt_array($ch, $curlConfig); + $response = curl_exec($ch); + + $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE); + if ($http_code !== 200) { + throw new \Exception('Error receiving data from url'); + } + curl_close($ch); + + return $response; + } + + private function getWeatherString($location) + { + if (empty($location)) { + return false; + } + + // try/catch + $data = $this->getWeather($location); + + $decode = json_decode($data, true); + if (empty($decode) || $decode['cod'] != 200) { + return false; + } + $city = $decode['name']; + $country = $decode['sys']['country']; + $temp = 'The temperature in ' . $city . ' (' . $country . ') is ' . $decode['main']['temp'] . '°C'; + $conditions = 'Current conditions are: ' . $decode['weather'][0]['description']; + + switch (strtolower($decode['weather'][0]['main'])) { + case 'clear': + $conditions.= ' ☀'; + break; + + case 'clouds': + $conditions.= ' ☁☁'; + break; + + case 'rain': + $conditions.= ' ☔'; + break; + + case 'thunderstorm': + $conditions.= ' ☔☔☔☔'; + break; + } + + return $temp . "\n" . $conditions; + } + + public function execute() + { + $update = $this->getUpdate(); + $message = $this->getMessage(); + + $chat_id = $message->getChat()->getId(); + $message_id = $message->getMessageId(); + $text = $message->getText(true); + + if (empty($text)) { + $text = 'You must specify location in format: /weather '; + } else { + $weather = $this->getWeatherString($text); + if (empty($weather)) { + $text = 'Can not find weather for location: ' . $text; + } else { + $text = $weather; + } + } + + $data = array(); + $data['chat_id'] = $chat_id; + $data['reply_to_message_id'] = $message_id; + $data['text'] = $text; + + $result = Request::sendMessage($data); + return $result; + } } diff --git a/src/Commands/WhoamiCommand.php b/src/Commands/WhoamiCommand.php index 69430b208..fdf4fcf6a 100644 --- a/src/Commands/WhoamiCommand.php +++ b/src/Commands/WhoamiCommand.php @@ -1,4 +1,5 @@ - */ +*/ namespace Longman\TelegramBot\Commands; @@ -18,34 +19,30 @@ class WhoamiCommand extends Command { - protected $name = 'whoami'; - protected $description = 'Show your id, name and username'; - protected $usage = '/whoami'; - protected $version = '1.0.0'; - protected $enabled = true; - - public function execute() { - $update = $this->getUpdate(); - $message = $this->getMessage(); - - - - $chat_id = $message->getChat()->getId(); - $message_id = $message->getMessageId(); - $text = $message->getText(true); - - $data = array(); - $data['chat_id'] = $chat_id; - $data['reply_to_message_id'] = $message_id; - $data['text'] = 'Your Id: ' . $message->getFrom()->getId(); - $data['text'] .= "\n".'Name: ' . $message->getFrom()->getFirstName().' '.$message->getFrom()->getLastName(); - $data['text'] .= "\n".'Username: ' . $message->getFrom()->getUsername(); - - - $result = Request::sendMessage($data); - return $result; - } - - + protected $name = 'whoami'; + protected $description = 'Show your id, name and username'; + protected $usage = '/whoami'; + protected $version = '1.0.0'; + protected $enabled = true; + + public function execute() + { + $update = $this->getUpdate(); + $message = $this->getMessage(); + + $chat_id = $message->getChat()->getId(); + $message_id = $message->getMessageId(); + $text = $message->getText(true); + + $data = array(); + $data['chat_id'] = $chat_id; + $data['reply_to_message_id'] = $message_id; + $data['text'] = 'Your Id: ' . $message->getFrom()->getId(); + $data['text'] .= "\n" . 'Name: ' . $message->getFrom()->getFirstName() + . ' ' . $message->getFrom()->getLastName(); + $data['text'] .= "\n" . 'Username: ' . $message->getFrom()->getUsername(); + + $result = Request::sendMessage($data); + return $result; + } } - diff --git a/src/Entities/Chat.php b/src/Entities/Chat.php index ec54d030d..f67ad4ec2 100644 --- a/src/Entities/Chat.php +++ b/src/Entities/Chat.php @@ -1,4 +1,5 @@ id = isset($data['id']) ? $data['id'] : null; - if (empty($this->id)) { - throw new TelegramException('id is empty!'); - } - - $this->title = isset($data['title']) ? $data['title'] : null; - $this->first_name = isset($data['first_name']) ? $data['first_name'] : null; - $this->last_name = isset($data['last_name']) ? $data['last_name'] : null; - $this->username = isset($data['username']) ? $data['username'] : null; - - } - + protected $id; + protected $title; + protected $first_name; + protected $last_name; + protected $username; - public function getId() { + public function __construct(array $data) + { - return $this->id; - } + $this->id = isset($data['id']) ? $data['id'] : null; + if (empty($this->id)) { + throw new TelegramException('id is empty!'); + } + $this->title = isset($data['title']) ? $data['title'] : null; + $this->first_name = isset($data['first_name']) ? $data['first_name'] : null; + $this->last_name = isset($data['last_name']) ? $data['last_name'] : null; + $this->username = isset($data['username']) ? $data['username'] : null; + } - public function getTitle() { + public function getId() + { - return $this->title; - } + return $this->id; + } - public function getFirstName() { + public function getTitle() + { - return $this->first_name; - } + return $this->title; + } - public function getLastName() { + public function getFirstName() + { - return $this->last_name; - } + return $this->first_name; + } + public function getLastName() + { - public function getUsername() { + return $this->last_name; + } - return $this->username; - } + public function getUsername() + { + return $this->username; + } } diff --git a/src/Entities/Entity.php b/src/Entities/Entity.php index b13ab0f7f..afea1aa8e 100644 --- a/src/Entities/Entity.php +++ b/src/Entities/Entity.php @@ -1,4 +1,5 @@ getProperties(); - public function toJSON() { - $reflection = new \ReflectionObject($this); - $properties = $reflection->getProperties(); - - $fields = array(); - - foreach($properties as $property) { - $name = $property->getName(); - $property->setAccessible(true); - $value = $property->getValue($this); - $fields[$name] = $value; - } - - $json = json_encode($fields); - - return $json; - } - - - - + $fields = array(); + foreach ($properties as $property) { + $name = $property->getName(); + $property->setAccessible(true); + $value = $property->getValue($this); + $fields[$name] = $value; + } + $json = json_encode($fields); + return $json; + } } diff --git a/src/Entities/Message.php b/src/Entities/Message.php index 91cf3e52d..1eb34387e 100644 --- a/src/Entities/Message.php +++ b/src/Entities/Message.php @@ -1,4 +1,5 @@ bot_name = $bot_name; + protected $sticker; - $this->message_id = isset($data['message_id']) ? $data['message_id'] : null; - if (empty($this->message_id)) { - throw new TelegramException('message_id is empty!'); - } + protected $video; - $this->from = isset($data['from']) ? $data['from'] : null; - if (empty($this->from)) { - throw new TelegramException('from is empty!'); - } - $this->from = new User($this->from); + protected $contact; + protected $location; - $this->date = isset($data['date']) ? $data['date'] : null; - if (empty($this->date)) { - throw new TelegramException('date is empty!'); - } + protected $new_chat_participant; - $this->chat = isset($data['chat']) ? $data['chat'] : null; - if (empty($this->chat)) { - throw new TelegramException('chat is empty!'); - } - $this->chat = new Chat($this->chat); + protected $left_chat_participant; + protected $new_chat_title; - $this->text = isset($data['text']) ? $data['text'] : null; + protected $new_chat_photo; + protected $delete_chat_photo; - $this->forward_from = isset($data['forward_from']) ? $data['forward_from'] : null; - if (!empty($this->forward_from)) { - $this->forward_from = new User($this->forward_from); - } + protected $group_chat_created; - $this->forward_date = isset($data['forward_date']) ? $data['forward_date'] : null; + protected $command; - $this->reply_to_message = isset($data['reply_to_message']) ? $data['reply_to_message'] : null; - if (!empty($this->reply_to_message)) { - $this->reply_to_message = new Message($this->reply_to_message); - } + protected $bot_name; - } + public function __construct(array $data, $bot_name) + { + $this->bot_name = $bot_name; - //return the entire command like /echo or /echo@bot1 if specified - public function getFullCommand(){ + $this->message_id = isset($data['message_id']) ? $data['message_id'] : null; + if (empty($this->message_id)) { + throw new TelegramException('message_id is empty!'); + } - return strtok($this->text, ' '); - } + $this->from = isset($data['from']) ? $data['from'] : null; + if (empty($this->from)) { + throw new TelegramException('from is empty!'); + } + $this->from = new User($this->from); + $this->date = isset($data['date']) ? $data['date'] : null; + if (empty($this->date)) { + throw new TelegramException('date is empty!'); + } - public function getCommand() { - if (!empty($this->_command)) { - return $this->_command; - } + $this->chat = isset($data['chat']) ? $data['chat'] : null; + if (empty($this->chat)) { + throw new TelegramException('chat is empty!'); + } + $this->chat = new Chat($this->chat); - $cmd = $this->getFullCommand(); + $this->text = isset($data['text']) ? $data['text'] : null; - if (substr($cmd, 0, 1) === '/') { - $cmd = substr($cmd, 1); + $this->forward_from = isset($data['forward_from']) ? $data['forward_from'] : null; + if (!empty($this->forward_from)) { + $this->forward_from = new User($this->forward_from); + } - //check if command is follow by botname - $split_cmd = explode('@', $cmd); - if (isset($split_cmd[1])) { - //command is followed by name check if is addressed to me - if (strtolower($split_cmd[1]) == strtolower($this->bot_name)){ - return $this->_command = $split_cmd[0]; - } - } else { - //command is not followed by name - return $this->_command = $cmd; - } - } + $this->forward_date = isset($data['forward_date']) ? $data['forward_date'] : null; - return false; - } + $this->reply_to_message = isset($data['reply_to_message']) ? $data['reply_to_message'] : null; + if (!empty($this->reply_to_message)) { + $this->reply_to_message = new Message($this->reply_to_message); + } + } + //return the entire command like /echo or /echo@bot1 if specified + public function getFullCommand() + { + return strtok($this->text, ' '); + } + public function getCommand() + { + if (!empty($this->command)) { + return $this->command; + } - public function getMessageId() { + $cmd = $this->getFullCommand(); - return $this->message_id; - } + if (substr($cmd, 0, 1) === '/') { + $cmd = substr($cmd, 1); - public function getDate() { + //check if command is follow by botname + $split_cmd = explode('@', $cmd); + if (isset($split_cmd[1])) { + //command is followed by name check if is addressed to me + if (strtolower($split_cmd[1]) == strtolower($this->bot_name)) { + return $this->command = $split_cmd[0]; + } + } else { + //command is not followed by name + return $this->command = $cmd; + } + } - return $this->date; - } + return false; + } - public function getFrom() { + public function getMessageId() + { - return $this->from; - } + return $this->message_id; + } + public function getDate() + { - public function getChat() { + return $this->date; + } - return $this->chat; - } + public function getFrom() + { - public function getForwardFrom() { + return $this->from; + } - return $this->forward_from; - } + public function getChat() + { - public function getForwardDate() { + return $this->chat; + } - return $this->forward_date; - } + public function getForwardFrom() + { - public function getReplyToMessage() { + return $this->forward_from; + } - return $this->reply_to_message; - } + public function getForwardDate() + { - public function getText($without_cmd = false) { - $text = $this->text; - if ($without_cmd) { - $command = $this->getFullCommand(); - $text = substr($text, strlen($command.' '), strlen($text)); - } + return $this->forward_date; + } - return $text; - } + public function getReplyToMessage() + { + return $this->reply_to_message; + } + public function getText($without_cmd = false) + { + $text = $this->text; + if ($without_cmd) { + $command = $this->getFullCommand(); + $text = substr($text, strlen($command . ' '), strlen($text)); + } + return $text; + } } diff --git a/src/Entities/Update.php b/src/Entities/Update.php index 9d382a69b..4dd5b20ed 100644 --- a/src/Entities/Update.php +++ b/src/Entities/Update.php @@ -1,4 +1,5 @@ bot_name = $bot_name; - $this->update_id = $update_id; - $this->message = new Message($message, $bot_name); + protected $update_id; + protected $message; + protected $bot_name; - } + public function __construct(array $data, $bot_name) + { - public function getUpdateId() { + $update_id = isset($data['update_id']) ? $data['update_id'] : null; - return $this->update_id; - } + $message = isset($data['message']) ? $data['message'] : null; + if (empty($update_id)) { + throw new TelegramException('update_id is empty!'); + } - public function getMessage() { + $this->bot_name = $bot_name; + $this->update_id = $update_id; + $this->message = new Message($message, $bot_name); + } - return $this->message; - } + public function getUpdateId() + { + return $this->update_id; + } + public function getMessage() + { + return $this->message; + } } diff --git a/src/Entities/User.php b/src/Entities/User.php index 86a8a55c9..43a942a8c 100644 --- a/src/Entities/User.php +++ b/src/Entities/User.php @@ -1,4 +1,5 @@ id = isset($data['id']) ? $data['id'] : null; - if (empty($this->id)) { - throw new TelegramException('id is empty!'); - } - - $this->first_name = isset($data['first_name']) ? $data['first_name'] : null; - if (empty($this->first_name)) { - throw new TelegramException('first_name is empty!'); - } - - $this->last_name = isset($data['last_name']) ? $data['last_name'] : null; - $this->username = isset($data['username']) ? $data['username'] : null; - - } - - - public function getId() { - - return $this->id; - } - - public function getFirstName() { - - return $this->first_name; - } + protected $id; + protected $first_name; + protected $last_name; + protected $username; - public function getLastName() { + public function __construct(array $data) + { - return $this->last_name; - } + $this->id = isset($data['id']) ? $data['id'] : null; + if (empty($this->id)) { + throw new TelegramException('id is empty!'); + } + $this->first_name = isset($data['first_name']) ? $data['first_name'] : null; + if (empty($this->first_name)) { + throw new TelegramException('first_name is empty!'); + } - public function getUsername() { + $this->last_name = isset($data['last_name']) ? $data['last_name'] : null; + $this->username = isset($data['username']) ? $data['username'] : null; + } - return $this->username; - } + public function getId() + { + return $this->id; + } + public function getFirstName() + { + return $this->first_name; + } + public function getLastName() + { + return $this->last_name; + } + public function getUsername() + { + return $this->username; + } } diff --git a/src/Exception/TelegramException.php b/src/Exception/TelegramException.php index f2a93e897..f5eb90410 100644 --- a/src/Exception/TelegramException.php +++ b/src/Exception/TelegramException.php @@ -6,13 +6,9 @@ * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. - */ +*/ namespace Longman\TelegramBot\Exception; - class TelegramException extends \Exception { - - - } diff --git a/src/Request.php b/src/Request.php index 571906224..aed8a407b 100644 --- a/src/Request.php +++ b/src/Request.php @@ -1,4 +1,5 @@ getCustomUpdate()) { - self::$input = $update; - } else { - self::$input = file_get_contents('php://input'); - } - self::log(); - return self::$input; - } - - - private static function log() { - if (!self::$telegram->getLogRequests()) { - return false; - } - $path = self::$telegram->getLogPath(); - if (!$path) { - return false; - } - - $status = file_put_contents($path, self::$input."\n", FILE_APPEND); - - return $status; - } - - - - public static function send($action, array $data = null) { - if (defined('PHPUNIT_TESTSUITE')) { - return $data; - } - - $ch = curl_init(); - $curlConfig = array( - CURLOPT_URL => 'https://api.telegram.org/bot'.self::$telegram->getApiKey().'/'.$action, - CURLOPT_POST => true, - CURLOPT_RETURNTRANSFER => true - ); - - if (!empty($data)) { - if (!empty($data['text']) && substr($data['text'], 0, 1) === '@') { - $data['text'] = ' '.$data['text']; - } - $curlConfig[CURLOPT_POSTFIELDS] = $data; - } - - - curl_setopt_array($ch, $curlConfig); - $result = curl_exec($ch); - curl_close($ch); - - return !empty($result) ? json_decode($result, true) : false; - } - - - - public static function sendMessage(array $data) { - - if (empty($data)) { - throw new TelegramException('Data is empty!'); - } - - $result = self::send('sendMessage', $data); - return $result; - } - - - public static function setWebhook($url) { - $result = self::send('setWebhook', array('url'=>$url)); - return $result; - } - - - - - + private static $telegram; + private static $input; + + private static $methods = array( + 'getMe', + 'sendMessage', + 'forwardMessage', + 'sendPhoto', + 'sendAudio', + 'sendDocument', + 'sendSticker', + 'sendVideo', + 'sendLocation', + 'sendChatAction', + 'getUserProfilePhotos', + 'getUpdates', + 'setWebhook', + ); + + public static function initialize(Telegram $telegram) + { + self::$telegram = $telegram; + } + + public static function getInput() + { + if ($update = self::$telegram->getCustomUpdate()) { + self::$input = $update; + } else { + self::$input = file_get_contents('php://input'); + } + self::log(); + return self::$input; + } + + private static function log() + { + if (!self::$telegram->getLogRequests()) { + return false; + } + $path = self::$telegram->getLogPath(); + if (!$path) { + return false; + } + + $status = file_put_contents($path, self::$input . "\n", FILE_APPEND); + + return $status; + } + + public static function send($action, array $data = null) + { + if (defined('PHPUNIT_TESTSUITE')) { + return $data; + } + + $ch = curl_init(); + $curlConfig = array( + CURLOPT_URL => 'https://api.telegram.org/bot' . self::$telegram->getApiKey() . '/' . $action, + CURLOPT_POST => true, + CURLOPT_RETURNTRANSFER => true + ); + + if (!empty($data)) { + if (!empty($data['text']) && substr($data['text'], 0, 1) === '@') { + $data['text'] = ' ' . $data['text']; + } + $curlConfig[CURLOPT_POSTFIELDS] = $data; + } + + curl_setopt_array($ch, $curlConfig); + $result = curl_exec($ch); + curl_close($ch); + + return !empty($result) ? json_decode($result, true) : false; + } + + public static function sendMessage(array $data) + { + + if (empty($data)) { + throw new TelegramException('Data is empty!'); + } + + $result = self::send('sendMessage', $data); + return $result; + } + + public static function setWebhook($url) + { + $result = self::send('setWebhook', array('url' => $url)); + return $result; + } } diff --git a/src/Telegram.php b/src/Telegram.php index 2690feed5..1ce9851c8 100644 --- a/src/Telegram.php +++ b/src/Telegram.php @@ -1,4 +1,5 @@ - * @copyright Avtandil Kikabidze - * @license http://opensource.org/licenses/mit-license.php The MIT License (MIT) - * @link http://www.github.com/akalongman/php-telegram-bot + * @package Telegram + * @author Avtandil Kikabidze + * @copyright Avtandil Kikabidze + * @license http://opensource.org/licenses/mit-license.php The MIT License (MIT) + * @link http://www.github.com/akalongman/php-telegram-bot */ class Telegram { - /** - * Version - * - * @var string - */ - protected $version = '0.0.5'; - - /** - * Telegram API key - * - * @var string - */ - protected $api_key = ''; - - /** - * Telegram Bot name - * - * @var string - */ - protected $bot_name = ''; - - - /** - * Raw request data - * - * @var string - */ - protected $input; - - /** - * Custom commands folder - * - * @var array - */ - protected $commands_dir = array(); - - /** - * Update object - * - * @var \Longman\TelegramBot\Entities\Update - */ - protected $update; - - /** - * Log Requests - * - * @var bool - */ - protected $log_requests; - - /** - * Log path - * - * @var string - */ - protected $log_path; - - /** - * MySQL Integration - * - * @var boolean - */ - protected $mysql_enabled; - - - /** - * MySQL credentials - * - * @var array - */ - protected $mysql_credentials = array(); - - - /** - * PDO object - * - * @var \PDO - */ - protected $pdo; - - - /** - * Constructor - * - * @param string $api_key - */ - public function __construct($api_key, $bot_name) { - if (empty($api_key)) { - throw new TelegramException('API KEY not defined!'); - } - - if (empty($bot_name)) { - throw new TelegramException('Bot Username not defined!'); - } - - - $this->api_key = $api_key; - $this->bot_name = $bot_name; - - Request::initialize($this); - } - - - /** - * Set custom update string for debug purposes - * - * @param string $update - * - * @return \Longman\TelegramBot\Telegram - */ - public function setCustomUpdate($update) { - $this->update = $update; - return $this; - } - - /** - * Get custom update string for debug purposes - * - * @return string $update - */ - public function getCustomUpdate() { - return $this->update; - } - - - /** - * Get commands list - * - * @return array $commands - */ - public function getCommandsList() { - - $commands = array(); - try { - $files = new \DirectoryIterator(BASE_PATH.'/Commands'); - } - catch(\Exception $e) { - throw new TelegramException('Can not open path: '.BASE_PATH.'/Commands'); - } - - foreach ($files as $fileInfo) { - if ($fileInfo->isDot()) continue; - $name = $fileInfo->getFilename(); - $name = strtolower(str_replace('Command.php', '', $name)); - $commands[$name] = $this->getCommandClass($name); - } - - if (!empty($this->commands_dir)) { - foreach ($this->commands_dir as $dir) { - if (!is_dir($dir)) { - continue; - } - - foreach (new \DirectoryIterator($dir) as $fileInfo) { - if ($fileInfo->isDot()) continue; - $name = $fileInfo->getFilename(); - $name = strtolower(str_replace('Command.php', '', $name)); - $commands[$name] = $this->getCommandClass($name); - } - } - } - - return $commands; - } - - - - - - /** - * Set log requests - * - * @param bool $log_requests - * - * @return \Longman\TelegramBot\Telegram - */ - public function setLogRequests($log_requests) { - $this->log_requests = $log_requests; - return $this; - } - - /** - * Get log requests - * - * @return bool - */ - public function getLogRequests() { - return $this->log_requests; - } - - - - /** - * Set log path - * - * @param string $log_path - * - * @return \Longman\TelegramBot\Telegram - */ - public function setLogPath($log_path) { - $this->log_path = $log_path; - return $this; - } - - /** - * Get log path - * - * @param string $log_path - * - * @return string - */ - public function getLogPath() { - return $this->log_path; - } - - /** - * Handle bot request - * - * @return \Longman\TelegramBot\Telegram - */ - public function handle() { - - - $this->input = Request::getInput(); - - - if (empty($this->input)) { - throw new TelegramException('Input is empty!'); - } - - - - $post = json_decode($this->input, true); - if (empty($post)) { - throw new TelegramException('Invalid JSON!'); - } - - - - $update = new Update($post, $this->bot_name); - - $this->insertRequest($update); - - $command = $update->getMessage()->getCommand(); - if (!empty($command)) { - return $this->executeCommand($command, $update); - } - - - - } - - /** - * Execute /command - * - * @return mixed - */ - protected function executeCommand($command, Update $update) { - $class = $this->getCommandClass($command, $update); - if (empty($class)) { - return false; - } - - return $class->execute(); - } - - /** - * Get command class - * - * @return object - */ - public function getCommandClass($command, Update $update = null) { - $this->commands_dir = array_unique($this->commands_dir); - $this->commands_dir = array_reverse($this->commands_dir); - $class_name = ucfirst($command).'Command'; - - foreach($this->commands_dir as $dir) { - if (is_file($dir.'/'.$class_name.'.php')) { - require_once($dir.'/'.$class_name.'.php'); - $class = new $class_name($this); - if (!empty($update)) { - $class->setUpdate($update); - } - - return $class; - } - } - - $class_name = __NAMESPACE__ . '\\Commands\\' . $class_name; - $class = new $class_name($this); - if (!empty($update)) { - $class->setUpdate($update); - } - - if (is_object($class)) { - return $class; - } - - return false; - } - - - /** - * Insert request in db - * - * @return bool - */ - protected function insertRequest(Update $update) { - if (empty($this->pdo)) { - return false; - } - - try { - $sth = $this->pdo->prepare('INSERT INTO `messages` - ( - `update_id`, `message_id`, `from`, `date`, `chat`, `forward_from`, - `forward_date`, `reply_to_message`, `text` - ) - VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)'); - - $message = $update->getMessage(); - - $update_id = $update->getUpdateId(); - $message_id = $message->getMessageId(); - $from = $message->getFrom()->toJSON(); - $date = $message->getDate(); - $chat = $message->getChat()->toJSON(); - $forward_from = $message->getForwardFrom(); - $forward_date = $message->getForwardDate(); - $reply_to_message = $message->getReplyToMessage(); - if (is_object($reply_to_message)) { - $reply_to_message = $reply_to_message->toJSON(); - } - $text = $message->getText(); - - - $sth->bindParam(1, $update_id, \PDO::PARAM_INT); - $sth->bindParam(2, $message_id, \PDO::PARAM_INT); - $sth->bindParam(3, $from, \PDO::PARAM_STR, 255); - $sth->bindParam(4, $date, \PDO::PARAM_INT); - $sth->bindParam(5, $chat, \PDO::PARAM_STR); - $sth->bindParam(6, $forward_from, \PDO::PARAM_STR); - $sth->bindParam(7, $forward_date, \PDO::PARAM_INT); - $sth->bindParam(8, $reply_to_message, \PDO::PARAM_STR); - $sth->bindParam(9, $text, \PDO::PARAM_STR); - - $status = $sth->execute(); - - - - - - /*$status = $executeQuery->execute( - array( - $update_id, $message_id, $from, $date, $chat, $forward_from, - $forward_date, $reply_to_message, $text, - ) - - );*/ - - - - } - catch(PDOException $e) { - throw new TelegramException($e->getMessage()); - } - - - return true; - } - - - /** - * Add custom commands path - * - * @return object - */ - public function addCommandsPath($folder) { - if (!is_dir($folder)) { - throw new TelegramException('Commands folder not exists!'); - } - $this->commands_dir[] = $folder; - return $this; - } - - /** - * Get API KEY - * - * @return string - */ - public function getApiKey() { - return $this->api_key; - } - - /** - * Get BOT NAME - * - * @return string - */ - public function getBotName() { - return $this->bot_name; - } - - /** - * Get Version - * - * @return string - */ - public function getVersion() { - return $this->version; - } - - /** - * Set Webhook for bot - * - * @return string - */ - public function setWebHook($url){ - if (empty($url)) { - throw new TelegramException('Hook url is empty!'); - } - $result = Request::setWebhook($url); - - if (!$result['ok']) { - throw new TelegramException('Webhook was not set! Error: '.$result['description']); - } - - return $result['description']; - } - - - /** - * Enable MySQL integration - * - * @param array $credentials MySQL credentials - * - * @return string - */ - public function enableMySQL(array $credentials){ - if (empty($credentials)) { - throw new TelegramException('MySQL credentials not provided!'); - } - $this->mysql_credentials = $credentials; - - $dsn = 'mysql:host='.$credentials['host'].';dbname='.$credentials['database']; - $options = array( - \PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8', - ); - try { - $pdo = new \PDO($dsn, $credentials['user'], $credentials['password'], $options); - $pdo->setAttribute (\PDO::ATTR_ERRMODE, \PDO::ERRMODE_WARNING); - } - catch (\PDOException $e) { - throw new TelegramException($e->getMessage()); - } - - $this->pdo = $pdo; - $this->mysql_enabled = true; - - return $this; - } - - + /** + * Version + * + * @var string + */ + protected $version = '0.0.5'; + + /** + * Telegram API key + * + * @var string + */ + protected $api_key = ''; + + /** + * Telegram Bot name + * + * @var string + */ + protected $bot_name = ''; + + /** + * Raw request data + * + * @var string + */ + protected $input; + + /** + * Custom commands folder + * + * @var array + */ + protected $commands_dir = array(); + + /** + * Update object + * + * @var \Longman\TelegramBot\Entities\Update + */ + protected $update; + + /** + * Log Requests + * + * @var bool + */ + protected $log_requests; + + /** + * Log path + * + * @var string + */ + protected $log_path; + + /** + * MySQL Integration + * + * @var boolean + */ + protected $mysql_enabled; + + /** + * MySQL credentials + * + * @var array + */ + protected $mysql_credentials = array(); + + /** + * PDO object + * + * @var \PDO + */ + protected $pdo; + + /** + * Constructor + * + * @param string $api_key + */ + public function __construct($api_key, $bot_name) + { + if (empty($api_key)) { + throw new TelegramException('API KEY not defined!'); + } + + if (empty($bot_name)) { + throw new TelegramException('Bot Username not defined!'); + } + + $this->api_key = $api_key; + $this->bot_name = $bot_name; + + Request::initialize($this); + } + + /** + * Set custom update string for debug purposes + * + * @param string $update + * + * @return \Longman\TelegramBot\Telegram + */ + public function setCustomUpdate($update) + { + $this->update = $update; + return $this; + } + + /** + * Get custom update string for debug purposes + * + * @return string $update + */ + public function getCustomUpdate() + { + return $this->update; + } + + /** + * Get commands list + * + * @return array $commands + */ + public function getCommandsList() + { + + $commands = array(); + try { + $files = new \DirectoryIterator(BASE_PATH . '/Commands'); + } catch (\Exception $e) { + throw new TelegramException('Can not open path: ' . BASE_PATH . '/Commands'); + } + + foreach ($files as $fileInfo) { + if ($fileInfo->isDot()) { + continue; + } + $name = $fileInfo->getFilename(); + $name = strtolower(str_replace('Command.php', '', $name)); + $commands[$name] = $this->getCommandClass($name); + } + + if (!empty($this->commands_dir)) { + foreach ($this->commands_dir as $dir) { + if (!is_dir($dir)) { + continue; + } + + foreach (new \DirectoryIterator($dir) as $fileInfo) { + if ($fileInfo->isDot()) { + continue; + } + $name = $fileInfo->getFilename(); + $name = strtolower(str_replace('Command.php', '', $name)); + $commands[$name] = $this->getCommandClass($name); + } + } + } + + return $commands; + } + + /** + * Set log requests + * + * @param bool $log_requests + * + * @return \Longman\TelegramBot\Telegram + */ + public function setLogRequests($log_requests) + { + $this->log_requests = $log_requests; + return $this; + } + + /** + * Get log requests + * + * @return bool + */ + public function getLogRequests() + { + return $this->log_requests; + } + + /** + * Set log path + * + * @param string $log_path + * + * @return \Longman\TelegramBot\Telegram + */ + public function setLogPath($log_path) + { + $this->log_path = $log_path; + return $this; + } + + /** + * Get log path + * + * @param string $log_path + * + * @return string + */ + public function getLogPath() + { + return $this->log_path; + } + + /** + * Handle bot request + * + * @return \Longman\TelegramBot\Telegram + */ + public function handle() + { + + $this->input = Request::getInput(); + + if (empty($this->input)) { + throw new TelegramException('Input is empty!'); + } + + $post = json_decode($this->input, true); + if (empty($post)) { + throw new TelegramException('Invalid JSON!'); + } + + $update = new Update($post, $this->bot_name); + + $this->insertRequest($update); + + $command = $update->getMessage()->getCommand(); + if (!empty($command)) { + return $this->executeCommand($command, $update); + } + } + + /** + * Execute /command + * + * @return mixed + */ + protected function executeCommand($command, Update $update) + { + $class = $this->getCommandClass($command, $update); + if (empty($class)) { + return false; + } + + return $class->execute(); + } + + /** + * Get command class + * + * @return object + */ + public function getCommandClass($command, Update $update = null) + { + $this->commands_dir = array_unique($this->commands_dir); + $this->commands_dir = array_reverse($this->commands_dir); + $class_name = ucfirst($command) . 'Command'; + + foreach ($this->commands_dir as $dir) { + if (is_file($dir . '/' . $class_name . '.php')) { + require_once($dir . '/' . $class_name . '.php'); + $class = new $class_name($this); + if (!empty($update)) { + $class->setUpdate($update); + } + + return $class; + } + } + + $class_name = __NAMESPACE__ . '\\Commands\\' . $class_name; + $class = new $class_name($this); + if (!empty($update)) { + $class->setUpdate($update); + } + + if (is_object($class)) { + return $class; + } + + return false; + } + + /** + * Insert request in db + * + * @return bool + */ + protected function insertRequest(Update $update) + { + if (empty($this->pdo)) { + return false; + } + + try { + $sth = $this->pdo->prepare('INSERT INTO `messages` + ( + `update_id`, `message_id`, `from`, `date`, `chat`, `forward_from`, + `forward_date`, `reply_to_message`, `text` + ) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)'); + + $message = $update->getMessage(); + + $update_id = $update->getUpdateId(); + $message_id = $message->getMessageId(); + $from = $message->getFrom()->toJSON(); + $date = $message->getDate(); + $chat = $message->getChat()->toJSON(); + $forward_from = $message->getForwardFrom(); + $forward_date = $message->getForwardDate(); + $reply_to_message = $message->getReplyToMessage(); + if (is_object($reply_to_message)) { + $reply_to_message = $reply_to_message->toJSON(); + } + $text = $message->getText(); + + $sth->bindParam(1, $update_id, \PDO::PARAM_INT); + $sth->bindParam(2, $message_id, \PDO::PARAM_INT); + $sth->bindParam(3, $from, \PDO::PARAM_STR, 255); + $sth->bindParam(4, $date, \PDO::PARAM_INT); + $sth->bindParam(5, $chat, \PDO::PARAM_STR); + $sth->bindParam(6, $forward_from, \PDO::PARAM_STR); + $sth->bindParam(7, $forward_date, \PDO::PARAM_INT); + $sth->bindParam(8, $reply_to_message, \PDO::PARAM_STR); + $sth->bindParam(9, $text, \PDO::PARAM_STR); + + $status = $sth->execute(); + + /*$status = $executeQuery->execute( + array( + $update_id, $message_id, $from, $date, $chat, $forward_from, + $forward_date, $reply_to_message, $text, + ) + + );*/ + } catch (PDOException $e) { + throw new TelegramException($e->getMessage()); + } + + return true; + } + + /** + * Add custom commands path + * + * @return object + */ + public function addCommandsPath($folder) + { + if (!is_dir($folder)) { + throw new TelegramException('Commands folder not exists!'); + } + $this->commands_dir[] = $folder; + return $this; + } + + /** + * Get API KEY + * + * @return string + */ + public function getApiKey() + { + return $this->api_key; + } + + /** + * Get BOT NAME + * + * @return string + */ + public function getBotName() + { + return $this->bot_name; + } + + /** + * Get Version + * + * @return string + */ + public function getVersion() + { + return $this->version; + } + + /** + * Set Webhook for bot + * + * @return string + */ + public function setWebHook($url) + { + if (empty($url)) { + throw new TelegramException('Hook url is empty!'); + } + $result = Request::setWebhook($url); + + if (!$result['ok']) { + throw new TelegramException('Webhook was not set! Error: ' . $result['description']); + } + + return $result['description']; + } + + /** + * Enable MySQL integration + * + * @param array $credentials MySQL credentials + * + * @return string + */ + public function enableMySQL(array $credentials) + { + if (empty($credentials)) { + throw new TelegramException('MySQL credentials not provided!'); + } + $this->mysql_credentials = $credentials; + + $dsn = 'mysql:host=' . $credentials['host'] . ';dbname=' . $credentials['database']; + $options = array(\PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8',); + try { + $pdo = new \PDO($dsn, $credentials['user'], $credentials['password'], $options); + $pdo->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_WARNING); + } catch (\PDOException $e) { + throw new TelegramException($e->getMessage()); + } + + $this->pdo = $pdo; + $this->mysql_enabled = true; + + return $this; + } }