Fix and improve User commands.

parent c9e38bc5
...@@ -42,7 +42,7 @@ class CancelCommand extends UserCommand ...@@ -42,7 +42,7 @@ class CancelCommand extends UserCommand
/** /**
* @var string * @var string
*/ */
protected $version = '0.1.1'; protected $version = '0.2.0';
/** /**
* @var bool * @var bool
...@@ -53,6 +53,7 @@ class CancelCommand extends UserCommand ...@@ -53,6 +53,7 @@ class CancelCommand extends UserCommand
* Command execute method * Command execute method
* *
* @return \Longman\TelegramBot\Entities\ServerResponse * @return \Longman\TelegramBot\Entities\ServerResponse
* @throws \Longman\TelegramBot\Exception\TelegramException
*/ */
public function execute() public function execute()
{ {
...@@ -72,22 +73,13 @@ class CancelCommand extends UserCommand ...@@ -72,22 +73,13 @@ class CancelCommand extends UserCommand
return $this->hideKeyboard($text); return $this->hideKeyboard($text);
} }
/**
* Execute no db
*
* @return \Longman\TelegramBot\Entities\ServerResponse
*/
public function executeNoDb()
{
return $this->hideKeyboard('Nothing to cancel.');
}
/** /**
* Hide the keyboard and output a text * Hide the keyboard and output a text
* *
* @param string $text * @param string $text
* *
* @return \Longman\TelegramBot\Entities\ServerResponse * @return \Longman\TelegramBot\Entities\ServerResponse
* @throws \Longman\TelegramBot\Exception\TelegramException
*/ */
private function hideKeyboard($text) private function hideKeyboard($text)
{ {
...@@ -99,4 +91,15 @@ class CancelCommand extends UserCommand ...@@ -99,4 +91,15 @@ class CancelCommand extends UserCommand
] ]
); );
} }
/**
* Execute no db
*
* @return \Longman\TelegramBot\Entities\ServerResponse
* @throws \Longman\TelegramBot\Exception\TelegramException
*/
public function executeNoDb()
{
return $this->hideKeyboard('Nothing to cancel.');
}
} }
...@@ -10,11 +10,13 @@ ...@@ -10,11 +10,13 @@
namespace Longman\TelegramBot\Commands\UserCommands; namespace Longman\TelegramBot\Commands\UserCommands;
use DateTime;
use DateTimeZone;
use GuzzleHttp\Client; use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException; use GuzzleHttp\Exception\RequestException;
use Longman\TelegramBot\Commands\UserCommand; use Longman\TelegramBot\Commands\UserCommand;
use Longman\TelegramBot\Exception\TelegramException;
use Longman\TelegramBot\Request; use Longman\TelegramBot\Request;
use Longman\TelegramBot\TelegramLog;
/** /**
* User "/date" command * User "/date" command
...@@ -39,7 +41,7 @@ class DateCommand extends UserCommand ...@@ -39,7 +41,7 @@ class DateCommand extends UserCommand
/** /**
* @var string * @var string
*/ */
protected $version = '1.3.0'; protected $version = '1.4.0';
/** /**
* Guzzle Client object * Guzzle Client object
...@@ -74,8 +76,7 @@ class DateCommand extends UserCommand ...@@ -74,8 +76,7 @@ class DateCommand extends UserCommand
* *
* @param string $location * @param string $location
* *
* @return array|boolean * @return array
* @throws \Longman\TelegramBot\Exception\TelegramException
*/ */
private function getCoordinates($location) private function getCoordinates($location)
{ {
...@@ -89,14 +90,16 @@ class DateCommand extends UserCommand ...@@ -89,14 +90,16 @@ class DateCommand extends UserCommand
try { try {
$response = $this->client->get($path, ['query' => $query]); $response = $this->client->get($path, ['query' => $query]);
} catch (RequestException $e) { } catch (RequestException $e) {
throw new TelegramException($e->getMessage()); TelegramLog::error($e->getMessage());
return [];
} }
if (!($result = $this->validateResponseData($response->getBody()))) { if (!($data = $this->validateResponseData($response->getBody()))) {
return false; return [];
} }
$result = $result['results'][0]; $result = $data['results'][0];
$lat = $result['geometry']['location']['lat']; $lat = $result['geometry']['location']['lat'];
$lng = $result['geometry']['location']['lng']; $lng = $result['geometry']['location']['lng'];
$acc = $result['geometry']['location_type']; $acc = $result['geometry']['location_type'];
...@@ -111,8 +114,7 @@ class DateCommand extends UserCommand ...@@ -111,8 +114,7 @@ class DateCommand extends UserCommand
* @param string $lat * @param string $lat
* @param string $lng * @param string $lng
* *
* @return array|boolean * @return array
* @throws \Longman\TelegramBot\Exception\TelegramException
*/ */
private function getDate($lat, $lng) private function getDate($lat, $lng)
{ {
...@@ -123,7 +125,7 @@ class DateCommand extends UserCommand ...@@ -123,7 +125,7 @@ class DateCommand extends UserCommand
$query = [ $query = [
'location' => urlencode($lat) . ',' . urlencode($lng), 'location' => urlencode($lat) . ',' . urlencode($lng),
'timestamp' => urlencode($timestamp) 'timestamp' => urlencode($timestamp),
]; ];
if ($this->google_api_key !== null) { if ($this->google_api_key !== null) {
...@@ -133,16 +135,18 @@ class DateCommand extends UserCommand ...@@ -133,16 +135,18 @@ class DateCommand extends UserCommand
try { try {
$response = $this->client->get($path, ['query' => $query]); $response = $this->client->get($path, ['query' => $query]);
} catch (RequestException $e) { } catch (RequestException $e) {
throw new TelegramException($e->getMessage()); TelegramLog::error($e->getMessage());
return [];
} }
if (!($result = $this->validateResponseData($response->getBody()))) { if (!($data = $this->validateResponseData($response->getBody()))) {
return false; return [];
} }
$local_time = $timestamp + $result['rawOffset'] + $result['dstOffset']; $local_time = $timestamp + $data['rawOffset'] + $data['dstOffset'];
return [$local_time, $result['timeZoneId']]; return [$local_time, $data['timeZoneId']];
} }
/** /**
...@@ -150,48 +154,48 @@ class DateCommand extends UserCommand ...@@ -150,48 +154,48 @@ class DateCommand extends UserCommand
* *
* @param string $data * @param string $data
* *
* @return bool|array * @return array
*/ */
private function validateResponseData($data) private function validateResponseData($data)
{ {
if (empty($data)) { if (empty($data)) {
return false; return [];
} }
$data = json_decode($data, true); $data = json_decode($data, true);
if (empty($data)) { if (empty($data)) {
return false; return [];
} }
if (isset($data['status']) && $data['status'] !== 'OK') { if (isset($data['status']) && $data['status'] !== 'OK') {
return false; return [];
} }
return $data; return $data;
} }
/** /**
* Get formatted date * Get formatted date at the passed location
* *
* @param string $location * @param string $location
* *
* @return string * @return string
* @throws \Longman\TelegramBot\Exception\TelegramException
*/ */
private function getFormattedDate($location) private function getFormattedDate($location)
{ {
if (empty($location)) { if ($location === null || $location === '') {
return 'The time in nowhere is never'; return 'The time in nowhere is never';
} }
list($lat, $lng, $acc, $types) = $this->getCoordinates($location); list($lat, $lng) = $this->getCoordinates($location);
if (empty($lat) || empty($lng)) { if (empty($lat) || empty($lng)) {
return 'It seems that in "' . $location . '" they do not have a concept of time.'; return 'It seems that in "' . $location . '" they do not have a concept of time.';
} }
list($local_time, $timezone_id) = $this->getDate($lat, $lng); list($local_time, $timezone_id) = $this->getDate($lat, $lng);
$date_utc = new \DateTime(gmdate('Y-m-d H:i:s', $local_time), new \DateTimeZone($timezone_id)); $date_utc = new DateTime(gmdate('Y-m-d H:i:s', $local_time), new DateTimeZone($timezone_id));
return 'The local time in ' . $timezone_id . ' is: ' . $date_utc->format($this->date_format); return 'The local time in ' . $timezone_id . ' is: ' . $date_utc->format($this->date_format);
} }
...@@ -200,6 +204,7 @@ class DateCommand extends UserCommand ...@@ -200,6 +204,7 @@ class DateCommand extends UserCommand
* Command execute method * Command execute method
* *
* @return mixed * @return mixed
* @throws \Longman\TelegramBot\Exception\TelegramException
*/ */
public function execute() public function execute()
{ {
...@@ -214,9 +219,9 @@ class DateCommand extends UserCommand ...@@ -214,9 +219,9 @@ class DateCommand extends UserCommand
$chat_id = $message->getChat()->getId(); $chat_id = $message->getChat()->getId();
$location = $message->getText(true); $location = $message->getText(true);
if (empty($location)) { $text = 'You must specify location in format: /date <city>';
$text = 'You must specify location in format: /date <city>';
} else { if ($location !== '') {
$text = $this->getFormattedDate($location); $text = $this->getFormattedDate($location);
} }
......
...@@ -36,12 +36,13 @@ class EchoCommand extends UserCommand ...@@ -36,12 +36,13 @@ class EchoCommand extends UserCommand
/** /**
* @var string * @var string
*/ */
protected $version = '1.0.1'; protected $version = '1.1.0';
/** /**
* Command execute method * Command execute method
* *
* @return mixed * @return mixed
* @throws \Longman\TelegramBot\Exception\TelegramException
*/ */
public function execute() public function execute()
{ {
......
...@@ -10,6 +10,7 @@ ...@@ -10,6 +10,7 @@
namespace Longman\TelegramBot\Commands\UserCommands; namespace Longman\TelegramBot\Commands\UserCommands;
use Longman\TelegramBot\Commands\Command;
use Longman\TelegramBot\Commands\UserCommand; use Longman\TelegramBot\Commands\UserCommand;
use Longman\TelegramBot\Request; use Longman\TelegramBot\Request;
...@@ -36,12 +37,13 @@ class HelpCommand extends UserCommand ...@@ -36,12 +37,13 @@ class HelpCommand extends UserCommand
/** /**
* @var string * @var string
*/ */
protected $version = '1.0.1'; protected $version = '1.1.0';
/** /**
* Command execute method * Command execute method
* *
* @return mixed * @return mixed
* @throws \Longman\TelegramBot\Exception\TelegramException
*/ */
public function execute() public function execute()
{ {
...@@ -52,26 +54,43 @@ class HelpCommand extends UserCommand ...@@ -52,26 +54,43 @@ class HelpCommand extends UserCommand
$command = trim($message->getText(true)); $command = trim($message->getText(true));
//Only get enabled Admin and User commands //Only get enabled Admin and User commands
$commands = array_filter($this->telegram->getCommandsList(), function ($command) { /** @var Command[] $command_objs */
return (!$command->isSystemCommand() && $command->isEnabled()); $command_objs = array_filter($this->telegram->getCommandsList(), function ($command_obj) {
/** @var Command $command_obj */
return !$command_obj->isSystemCommand() && $command_obj->isEnabled();
}); });
//If no command parameter is passed, show the list //If no command parameter is passed, show the list
if ($command === '') { if ($command === '') {
$text = $this->telegram->getBotName() . ' v. ' . $this->telegram->getVersion() . "\n\n"; $text = sprintf(
$text .= 'Commands List:' . "\n"; '%s v. %s' . PHP_EOL . PHP_EOL . 'Commands List:' . PHP_EOL,
foreach ($commands as $command) { $this->telegram->getBotName(),
$text .= '/' . $command->getName() . ' - ' . $command->getDescription() . "\n"; $this->telegram->getVersion()
);
foreach ($command_objs as $command) {
$text .= sprintf(
'/%s - %s' . PHP_EOL,
$command->getName(),
$command->getDescription()
);
} }
$text .= "\n" . 'For exact command help type: /help <command>'; $text .= PHP_EOL . 'For exact command help type: /help <command>';
} else { } else {
$command = str_replace('/', '', $command); $command = str_replace('/', '', $command);
if (isset($commands[$command])) { if (isset($command_objs[$command])) {
$command = $commands[$command]; /** @var Command $command_obj */
$text = 'Command: ' . $command->getName() . ' v' . $command->getVersion() . "\n"; $command_obj = $command_objs[$command];
$text .= 'Description: ' . $command->getDescription() . "\n"; $text = sprintf(
$text .= 'Usage: ' . $command->getUsage(); 'Command: %s v%s' . PHP_EOL .
'Description: %s' . PHP_EOL .
'Usage: %s',
$command_obj->getName(),
$command_obj->getVersion(),
$command_obj->getDescription(),
$command_obj->getUsage()
);
} else { } else {
$text = 'No help available: Command /' . $command . ' not found'; $text = 'No help available: Command /' . $command . ' not found';
} }
......
...@@ -36,20 +36,20 @@ class SlapCommand extends UserCommand ...@@ -36,20 +36,20 @@ class SlapCommand extends UserCommand
/** /**
* @var string * @var string
*/ */
protected $version = '1.0.1'; protected $version = '1.1.0';
/** /**
* Command execute method * Command execute method
* *
* @return mixed * @return mixed
* @throws \Longman\TelegramBot\Exception\TelegramException
*/ */
public function execute() public function execute()
{ {
$message = $this->getMessage(); $message = $this->getMessage();
$chat_id = $message->getChat()->getId(); $chat_id = $message->getChat()->getId();
$message_id = $message->getMessageId(); $text = $message->getText(true);
$text = $message->getText(true);
$sender = '@' . $message->getFrom()->getUsername(); $sender = '@' . $message->getFrom()->getUsername();
......
This diff is collapsed.
...@@ -10,11 +10,12 @@ ...@@ -10,11 +10,12 @@
namespace Longman\TelegramBot\Commands\UserCommands; namespace Longman\TelegramBot\Commands\UserCommands;
use Exception;
use GuzzleHttp\Client; use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException; use GuzzleHttp\Exception\RequestException;
use Longman\TelegramBot\Commands\UserCommand; use Longman\TelegramBot\Commands\UserCommand;
use Longman\TelegramBot\Exception\TelegramException;
use Longman\TelegramBot\Request; use Longman\TelegramBot\Request;
use Longman\TelegramBot\TelegramLog;
/** /**
* User "/weather" command * User "/weather" command
...@@ -39,7 +40,7 @@ class WeatherCommand extends UserCommand ...@@ -39,7 +40,7 @@ class WeatherCommand extends UserCommand
/** /**
* @var string * @var string
*/ */
protected $version = '1.1.0'; protected $version = '1.2.0';
/** /**
* Base URI for OpenWeatherMap API * Base URI for OpenWeatherMap API
...@@ -54,7 +55,6 @@ class WeatherCommand extends UserCommand ...@@ -54,7 +55,6 @@ class WeatherCommand extends UserCommand
* @param string $location * @param string $location
* *
* @return string * @return string
* @throws \Longman\TelegramBot\Exception\TelegramException
*/ */
private function getWeatherData($location) private function getWeatherData($location)
{ {
...@@ -69,7 +69,9 @@ class WeatherCommand extends UserCommand ...@@ -69,7 +69,9 @@ class WeatherCommand extends UserCommand
try { try {
$response = $client->get($path, ['query' => $query]); $response = $client->get($path, ['query' => $query]);
} catch (RequestException $e) { } catch (RequestException $e) {
throw new TelegramException($e->getMessage()); TelegramLog::error($e->getMessage());
return '';
} }
return (string)$response->getBody(); return (string)$response->getBody();
...@@ -80,13 +82,13 @@ class WeatherCommand extends UserCommand ...@@ -80,13 +82,13 @@ class WeatherCommand extends UserCommand
* *
* @param array $data * @param array $data
* *
* @return bool|string * @return string
*/ */
private function getWeatherString(array $data) private function getWeatherString(array $data)
{ {
try { try {
if (empty($data) || $data['cod'] !== 200) { if (!(isset($data['cod']) && $data['cod'] === 200)) {
return false; return '';
} }
//http://openweathermap.org/weather-conditions //http://openweathermap.org/weather-conditions
...@@ -101,16 +103,18 @@ class WeatherCommand extends UserCommand ...@@ -101,16 +103,18 @@ class WeatherCommand extends UserCommand
$conditions_now = strtolower($data['weather'][0]['main']); $conditions_now = strtolower($data['weather'][0]['main']);
return sprintf( return sprintf(
'The temperature in %1$s (%2$s) is %3$s°C' . "\n" . 'The temperature in %s (%s) is %s°C' . "\n" .
'Current conditions are: %4$s%5$s', 'Current conditions are: %s%s',
$data['name'], //city $data['name'], //city
$data['sys']['country'], //country $data['sys']['country'], //country
$data['main']['temp'], //temperature $data['main']['temp'], //temperature
$data['weather'][0]['description'], //description of weather $data['weather'][0]['description'], //description of weather
(isset($conditions[$conditions_now])) ? $conditions[$conditions_now] : '' isset($conditions[$conditions_now]) ? $conditions[$conditions_now] : ''
); );
} catch (\Exception $e) { } catch (Exception $e) {
return false; TelegramLog::error($e->getMessage());
return '';
} }
} }
...@@ -118,6 +122,7 @@ class WeatherCommand extends UserCommand ...@@ -118,6 +122,7 @@ class WeatherCommand extends UserCommand
* Command execute method * Command execute method
* *
* @return mixed * @return mixed
* @throws \Longman\TelegramBot\Exception\TelegramException
*/ */
public function execute() public function execute()
{ {
...@@ -126,11 +131,12 @@ class WeatherCommand extends UserCommand ...@@ -126,11 +131,12 @@ class WeatherCommand extends UserCommand
$text = ''; $text = '';
if (trim($this->getConfig('owm_api_key'))) { if (trim($this->getConfig('owm_api_key'))) {
if ($location = trim($message->getText(true))) { $location = trim($message->getText(true));
if ($location !== '') {
if ($weather_data = json_decode($this->getWeatherData($location), true)) { if ($weather_data = json_decode($this->getWeatherData($location), true)) {
$text = $this->getWeatherString($weather_data); $text = $this->getWeatherString($weather_data);
} }
if (!$text) { if ($text === '') {
$text = 'Cannot find weather for location: ' . $location; $text = 'Cannot find weather for location: ' . $location;
} }
} else { } else {
......
...@@ -14,6 +14,8 @@ namespace Longman\TelegramBot\Commands\UserCommands; ...@@ -14,6 +14,8 @@ namespace Longman\TelegramBot\Commands\UserCommands;
use Longman\TelegramBot\Commands\UserCommand; use Longman\TelegramBot\Commands\UserCommand;
use Longman\TelegramBot\Entities\File; use Longman\TelegramBot\Entities\File;
use Longman\TelegramBot\Entities\PhotoSize;
use Longman\TelegramBot\Entities\UserProfilePhotos;
use Longman\TelegramBot\Request; use Longman\TelegramBot\Request;
/** /**
...@@ -39,81 +41,86 @@ class WhoamiCommand extends UserCommand ...@@ -39,81 +41,86 @@ class WhoamiCommand extends UserCommand
/** /**
* @var string * @var string
*/ */
protected $version = '1.0.1'; protected $version = '1.1.0';
/**
* @var bool
*/
protected $public = true;
/** /**
* Command execute method * Command execute method
* *
* @return mixed * @return mixed
* @throws \Longman\TelegramBot\Exception\TelegramException
*/ */
public function execute() public function execute()
{ {
$message = $this->getMessage(); $message = $this->getMessage();
$user_id = $message->getFrom()->getId(); $from = $message->getFrom();
$user_id = $from->getId();
$chat_id = $message->getChat()->getId(); $chat_id = $message->getChat()->getId();
$message_id = $message->getMessageId(); $message_id = $message->getMessageId();
$text = $message->getText(true);
//Send chat action
Request::sendChatAction(['chat_id' => $chat_id, 'action' => 'typing']);
$caption = 'Your Id: ' . $user_id . "\n";
$caption .= 'Name: ' . $message->getFrom()->getFirstName()
. ' ' . $message->getFrom()->getLastName() . "\n";
$caption .= 'Username: ' . $message->getFrom()->getUsername();
//Fetch user profile photo
$limit = 10;
$offset = null;
$ServerResponse = Request::getUserProfilePhotos([
'user_id' => $user_id,
'limit' => $limit,
'offset' => $offset,
]);
//Check if the request isOK
if ($ServerResponse->isOk()) {
$UserProfilePhoto = $ServerResponse->getResult();
$totalcount = $UserProfilePhoto->getTotalCount();
} else {
$totalcount = 0;
}
$data = [ $data = [
'chat_id' => $chat_id, 'chat_id' => $chat_id,
'reply_to_message_id' => $message_id, 'reply_to_message_id' => $message_id,
]; ];
if ($totalcount > 0) { //Send chat action
$photos = $UserProfilePhoto->getPhotos(); Request::sendChatAction([
//I pick the latest photo with the hight definition 'chat_id' => $chat_id,
$photo = $photos[0][2]; 'action' => 'typing',
$file_id = $photo->getFileId(); ]);
$data['photo'] = $file_id; $caption = sprintf(
$data['caption'] = $caption; 'Your Id: %d' . PHP_EOL .
'Name: %s %s' . PHP_EOL .
$result = Request::sendPhoto($data); 'Username: %s',
$user_id,
$from->getFirstName(),
$from->getLastName(),
$from->getUsername()
);
//Download the image pictures //Fetch user profile photo
//Download after send message response to speedup response $limit = 10;
$file_id = $photo->getFileId(); $offset = null;
$ServerResponse = Request::getFile(['file_id' => $file_id]); $response = Request::getUserProfilePhotos(
if ($ServerResponse->isOk()) { [
Request::downloadFile($ServerResponse->getResult()); 'user_id' => $user_id,
'limit' => $limit,
'offset' => $offset,
]
);
if ($response->isOk()) {
/** @var UserProfilePhotos $user_profile_photos */
$user_profile_photos = $response->getResult();
if ($user_profile_photos->getTotalCount() > 0) {
$photos = $user_profile_photos->getPhotos();
/** @var PhotoSize $photo */
$photo = $photos[0][2];
$file_id = $photo->getFileId();
$data['photo'] = $file_id;
$data['caption'] = $caption;
$result = Request::sendPhoto($data);
//Download the photo after send message response to speedup response
$response2 = Request::getFile(['file_id' => $file_id]);
if ($response2->isOk()) {
/** @var File $photo_file */
$photo_file = $response2->getResult();
Request::downloadFile($photo_file);
}
return $result;
} }
} else {
//No Photo just send text
$data['text'] = $caption;
$result = Request::sendMessage($data);
} }
return $result; //No Photo just send text
$data['text'] = $caption;
return Request::sendMessage($data);
} }
} }
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment