Commit 818c3c84 authored by Armando Lüscher's avatar Armando Lüscher Committed by GitHub

Merge pull request #288 from noplanman/scrutinizer_fixes

Scrutinizer fixes
parents 005f781e b4713f3b
tools: tools:
external_code_coverage: external_code_coverage:
timeout: 600 timeout: 600
\ No newline at end of file
filter:
paths: ["src/*"]
...@@ -25,7 +25,7 @@ class ForceReplyCommand extends UserCommand ...@@ -25,7 +25,7 @@ class ForceReplyCommand extends UserCommand
protected $name = 'forcereply'; protected $name = 'forcereply';
protected $description = 'Force reply with reply markup'; protected $description = 'Force reply with reply markup';
protected $usage = '/forcereply'; protected $usage = '/forcereply';
protected $version = '0.0.5'; protected $version = '0.0.6';
/**#@-*/ /**#@-*/
/** /**
...@@ -36,10 +36,11 @@ class ForceReplyCommand extends UserCommand ...@@ -36,10 +36,11 @@ class ForceReplyCommand extends UserCommand
$message = $this->getMessage(); $message = $this->getMessage();
$chat_id = $message->getChat()->getId(); $chat_id = $message->getChat()->getId();
$data = []; $data = [
$data['chat_id'] = $chat_id; 'chat_id' => $chat_id,
$data['text'] = 'Write something:'; 'text' => 'Write something:',
$data['reply_markup'] = new ForceReply(['selective' => false]); 'reply_markup' => new ForceReply(['selective' => false]),
];
return Request::sendMessage($data); return Request::sendMessage($data);
} }
......
...@@ -25,7 +25,7 @@ class ImageCommand extends UserCommand ...@@ -25,7 +25,7 @@ class ImageCommand extends UserCommand
protected $name = 'image'; protected $name = 'image';
protected $description = 'Send Image'; protected $description = 'Send Image';
protected $usage = '/image'; protected $usage = '/image';
protected $version = '1.0.0'; protected $version = '1.0.1';
/**#@-*/ /**#@-*/
/** /**
...@@ -35,20 +35,28 @@ class ImageCommand extends UserCommand ...@@ -35,20 +35,28 @@ class ImageCommand extends UserCommand
{ {
$message = $this->getMessage(); $message = $this->getMessage();
$chat_id = $message->getChat()->getId(); $chat_id = $message->getChat()->getId();
$text = $message->getText(true); $text = $message->getText(true);
$data = []; $data = [
$data['chat_id'] = $chat_id; 'chat_id' => $chat_id,
$data['caption'] = $text; 'caption' => $text,
];
//return Request::sendPhoto($data, $this->telegram->getUploadPath().'/'.'image.jpg'); //Return a random picture from the telegram->getUploadPath().
return Request::sendPhoto($data, $this->ShowRandomImage($this->telegram->getUploadPath())); return Request::sendPhoto($data, $this->ShowRandomImage($this->telegram->getUploadPath()));
} }
//return random picture from the telegram->getUploadPath();
private function ShowRandomImage($dir) {
$image_list = scandir($dir);
return $dir . "/" . $image_list[mt_rand(2, count($image_list) - 1)];
}
/**
* Return the path to a random image in the passed directory.
*
* @param string $dir
*
* @return string
*/
private function ShowRandomImage($dir)
{
$image_list = scandir($dir);
return $dir . '/' . $image_list[mt_rand(2, count($image_list) - 1)];
}
} }
...@@ -26,7 +26,7 @@ class InlinekeyboardCommand extends UserCommand ...@@ -26,7 +26,7 @@ class InlinekeyboardCommand extends UserCommand
protected $name = 'Inlinekeyboard'; protected $name = 'Inlinekeyboard';
protected $description = 'Show inline keyboard'; protected $description = 'Show inline keyboard';
protected $usage = '/inlinekeyboard'; protected $usage = '/inlinekeyboard';
protected $version = '0.0.1'; protected $version = '0.0.2';
/**#@-*/ /**#@-*/
/** /**
...@@ -37,13 +37,13 @@ class InlinekeyboardCommand extends UserCommand ...@@ -37,13 +37,13 @@ class InlinekeyboardCommand extends UserCommand
$message = $this->getMessage(); $message = $this->getMessage();
$inline_keyboard = [ $inline_keyboard = [
new InlineKeyboardButton(['text' => 'inline', 'switch_inline_query' => 'true']), new InlineKeyboardButton(['text' => 'inline', 'switch_inline_query' => 'true']),
new InlineKeyboardButton(['text' => 'callback', 'callback_data' => 'identifier']), new InlineKeyboardButton(['text' => 'callback', 'callback_data' => 'identifier']),
new InlineKeyboardButton(['text' => 'open url', 'url' => 'https://github.com/akalongman/php-telegram-bot']), new InlineKeyboardButton(['text' => 'open url', 'url' => 'https://github.com/akalongman/php-telegram-bot']),
]; ];
$data = [ $data = [
'chat_id' => $message->getChat()->getId(), 'chat_id' => $message->getChat()->getId(),
'text' => 'inline keyboard', 'text' => 'inline keyboard',
'reply_markup' => new InlineKeyboardMarkup(['inline_keyboard' => [$inline_keyboard]]), 'reply_markup' => new InlineKeyboardMarkup(['inline_keyboard' => [$inline_keyboard]]),
]; ];
......
...@@ -23,9 +23,9 @@ class KeyboardCommand extends UserCommand ...@@ -23,9 +23,9 @@ class KeyboardCommand extends UserCommand
* {@inheritdoc} * {@inheritdoc}
*/ */
protected $name = 'keyboard'; protected $name = 'keyboard';
protected $description = 'Show a custom keybord with reply markup'; protected $description = 'Show a custom keyboard with reply markup';
protected $usage = '/keyboard'; protected $usage = '/keyboard';
protected $version = '0.0.6'; protected $version = '0.1.0';
/**#@-*/ /**#@-*/
/** /**
...@@ -35,70 +35,67 @@ class KeyboardCommand extends UserCommand ...@@ -35,70 +35,67 @@ class KeyboardCommand extends UserCommand
{ {
$message = $this->getMessage(); $message = $this->getMessage();
$chat_id = $message->getChat()->getId(); $chat_id = $message->getChat()->getId();
$text = $message->getText(true);
$data = []; $data = [
$data['chat_id'] = $chat_id; 'chat_id' => $chat_id,
$data['text'] = 'Press a Button:'; 'text' => 'Press a Button:',
];
//Keyboard examples //Keyboard examples
$keyboards = []; $keyboards = [];
//0 //Example 0
$keyboard[] = ['7','8','9']; $keyboard = [];
$keyboard[] = ['4','5','6']; $keyboard[] = ['7', '8', '9'];
$keyboard[] = ['1','2','3']; $keyboard[] = ['4', '5', '6'];
$keyboard[] = [' ','0',' ']; $keyboard[] = ['1', '2', '3'];
$keyboard[] = [' ', '0', ' '];
$keyboards[] = $keyboard; $keyboards[] = $keyboard;
unset($keyboard);
//1
$keyboard[] = ['7','8','9','+'];
$keyboard[] = ['4','5','6','-'];
$keyboard[] = ['1','2','3','*'];
$keyboard[] = [' ','0',' ','/'];
//Example 1
$keyboard = [];
$keyboard[] = ['7', '8', '9', '+'];
$keyboard[] = ['4', '5', '6', '-'];
$keyboard[] = ['1', '2', '3', '*'];
$keyboard[] = [' ', '0', ' ', '/'];
$keyboards[] = $keyboard; $keyboards[] = $keyboard;
unset($keyboard);
//2
$keyboard[] = ['A'];
$keyboard[] = ['B'];
$keyboard[] = ['C'];
//Example 2
$keyboard = [];
$keyboard[] = ['A'];
$keyboard[] = ['B'];
$keyboard[] = ['C'];
$keyboards[] = $keyboard; $keyboards[] = $keyboard;
unset($keyboard);
//3
$keyboard[] = ['A'];
$keyboard[] = ['B'];
$keyboard[] = ['C','D'];
//Example 3
$keyboard = [];
$keyboard[] = ['A'];
$keyboard[] = ['B'];
$keyboard[] = ['C', 'D'];
$keyboards[] = $keyboard; $keyboards[] = $keyboard;
unset($keyboard);
//4 (bots 2.0) //Example 4 (bots version 2.0)
$keyboard[] = [ $keyboard = [];
$keyboard[] = [
[ [
'text' => 'request_contact', 'text' => 'Send my contact',
'request_contact' => true 'request_contact' => true,
], ],
[ [
'text' => 'request_location', 'text' => 'Send my location',
'request_location' => true 'request_location' => true,
] ],
]; ];
$keyboards[] = $keyboard; $keyboards[] = $keyboard;
unset($keyboard);
//Return a random keyboard.
$keyboard = $keyboards[mt_rand(0, count($keyboards) - 1)];
$data['reply_markup'] = new ReplyKeyboardMarkup( $data['reply_markup'] = new ReplyKeyboardMarkup(
[ [
'keyboard' => $keyboards[1] , 'keyboard' => $keyboard,
'resize_keyboard' => true, 'resize_keyboard' => true,
'one_time_keyboard' => false, 'one_time_keyboard' => false,
'selective' => false 'selective' => false,
] ]
); );
......
...@@ -25,7 +25,7 @@ class MarkdownCommand extends UserCommand ...@@ -25,7 +25,7 @@ class MarkdownCommand extends UserCommand
protected $name = 'markdown'; protected $name = 'markdown';
protected $description = 'Print Markdown tesxt'; protected $description = 'Print Markdown tesxt';
protected $usage = '/markdown'; protected $usage = '/markdown';
protected $version = '1.0.0'; protected $version = '1.0.1';
/**#@-*/ /**#@-*/
/** /**
...@@ -35,17 +35,18 @@ class MarkdownCommand extends UserCommand ...@@ -35,17 +35,18 @@ class MarkdownCommand extends UserCommand
{ {
$message = $this->getMessage(); $message = $this->getMessage();
$chat_id = $message->getChat()->getId(); $chat_id = $message->getChat()->getId();
$text = $message->getText(true);
$data = []; $data = [
$data['chat_id'] = $chat_id; 'chat_id' => $chat_id,
$data['parse_mode'] = 'MARKDOWN'; 'parse_mode' => 'MARKDOWN',
$data['text'] = "*bold* _italic_ `inline fixed width code` ```preformatted code block 'text' => '*bold* _italic_ `inline fixed width code`
```
preformatted code block
code block code block
``` ```
[Best Telegram bot api!!](https://github.com/akalongman/php-telegram-bot) [Best Telegram bot api!!](https://github.com/akalongman/php-telegram-bot)
',
"; ];
return Request::sendMessage($data); return Request::sendMessage($data);
} }
......
...@@ -78,7 +78,7 @@ class Botan ...@@ -78,7 +78,7 @@ class Botan
*/ */
public static function track($input, $command = '') public static function track($input, $command = '')
{ {
if (empty(self::$token) || $command != self::$command) { if (empty(self::$token) || $command !== self::$command) {
return false; return false;
} }
...@@ -88,17 +88,18 @@ class Botan ...@@ -88,17 +88,18 @@ class Botan
self::$command = ''; self::$command = '';
$obj = json_decode($input, true); $obj = json_decode($input, true);
$data = [];
if (isset($obj['message'])) { if (isset($obj['message'])) {
$data = $obj['message']; $data = $obj['message'];
$event_name = 'Message'; $event_name = 'Message';
if (isset($obj['message']['entities']) && is_array($obj['message']['entities'])) { if (isset($obj['message']['entities']) && is_array($obj['message']['entities'])) {
foreach ($obj['message']['entities'] as $entity) { foreach ($obj['message']['entities'] as $entity) {
if ($entity['type'] == 'bot_command' && $entity['offset'] == 0) { if ($entity['type'] === 'bot_command' && $entity['offset'] === 0) {
if (strtolower($command) == 'generic') { if (strtolower($command) === 'generic') {
$command = 'Generic'; $command = 'Generic';
} elseif (strtolower($command) == 'genericmessage') { } elseif (strtolower($command) === 'genericmessage') {
$command = 'Generic Message'; $command = 'Generic Message';
} else { } else {
$command = '/' . strtolower($command); $command = '/' . strtolower($command);
...@@ -136,15 +137,15 @@ class Botan ...@@ -136,15 +137,15 @@ class Botan
'header' => 'Content-Type: application/json', 'header' => 'Content-Type: application/json',
'method' => 'POST', 'method' => 'POST',
'content' => json_encode($data), 'content' => json_encode($data),
'ignore_errors' => true 'ignore_errors' => true,
] ],
]; ];
$context = stream_context_create($options); $context = stream_context_create($options);
$response = @file_get_contents($request, false, $context); $response = @file_get_contents($request, false, $context);
$responseData = json_decode($response, true); $responseData = json_decode($response, true);
if ($responseData['status'] != 'accepted') { if ($responseData['status'] !== 'accepted') {
error_log('Botan.io API replied with error: ' . $response); error_log('Botan.io API replied with error: ' . $response);
} }
...@@ -171,7 +172,6 @@ class Botan ...@@ -171,7 +172,6 @@ class Botan
} }
$cached = BotanDB::selectShortUrl($user_id, $url); $cached = BotanDB::selectShortUrl($user_id, $url);
if (!empty($cached[0]['short_url'])) { if (!empty($cached[0]['short_url'])) {
return $cached[0]['short_url']; return $cached[0]['short_url'];
} }
...@@ -185,8 +185,8 @@ class Botan ...@@ -185,8 +185,8 @@ class Botan
$options = [ $options = [
'http' => [ 'http' => [
'ignore_errors' => true, 'ignore_errors' => true,
'timeout' => 3 'timeout' => 3,
] ],
]; ];
$context = stream_context_create($options); $context = stream_context_create($options);
...@@ -197,6 +197,7 @@ class Botan ...@@ -197,6 +197,7 @@ class Botan
} else { } else {
// @TODO: Add telegram log // @TODO: Add telegram log
error_log('Botan.io API replied with error: ' . $response); error_log('Botan.io API replied with error: ' . $response);
return $url; return $url;
} }
......
...@@ -35,9 +35,8 @@ class BotanDB extends DB ...@@ -35,9 +35,8 @@ class BotanDB extends DB
* @param $user_id * @param $user_id
* @param $url * @param $url
* *
* @return array|bool
* @throws \Longman\TelegramBot\Exception\TelegramException * @throws \Longman\TelegramBot\Exception\TelegramException
*
* @return bool|string
*/ */
public static function selectShortUrl($user_id, $url) public static function selectShortUrl($user_id, $url)
{ {
...@@ -48,30 +47,27 @@ class BotanDB extends DB ...@@ -48,30 +47,27 @@ class BotanDB extends DB
try { try {
$sth = self::$pdo->prepare('SELECT * FROM `' . TB_BOTAN_SHORTENER . '` $sth = self::$pdo->prepare('SELECT * FROM `' . TB_BOTAN_SHORTENER . '`
WHERE `user_id` = :user_id AND `url` = :url WHERE `user_id` = :user_id AND `url` = :url
'); ');
$sth->bindParam(':user_id', $user_id, PDO::PARAM_INT); $sth->bindParam(':user_id', $user_id, PDO::PARAM_INT);
$sth->bindParam(':url', $url, PDO::PARAM_INT); $sth->bindParam(':url', $url, PDO::PARAM_INT);
$sth->execute(); $sth->execute();
$results = $sth->fetchAll(PDO::FETCH_ASSOC); return $sth->fetchAll(PDO::FETCH_ASSOC);
} catch (Exception $e) { } catch (Exception $e) {
throw new TelegramException($e->getMessage()); throw new TelegramException($e->getMessage());
} }
return $results;
} }
/** /**
* Insert shortened URL into the database * Insert shortened URL into the database
* *
* @param $user_id * @param $user_id
* @param $url * @param $url
* @param $short_url * @param $short_url
*
* @throws \Longman\TelegramBot\Exception\TelegramException
* *
* @return bool * @return bool
* @throws \Longman\TelegramBot\Exception\TelegramException
*/ */
public static function insertShortUrl($user_id, $url, $short_url) public static function insertShortUrl($user_id, $url, $short_url)
{ {
...@@ -87,7 +83,7 @@ class BotanDB extends DB ...@@ -87,7 +83,7 @@ class BotanDB extends DB
VALUES ( VALUES (
:user_id, :url, :short_url, :date :user_id, :url, :short_url, :date
) )
'); ');
$created_at = self::getTimestamp(); $created_at = self::getTimestamp();
...@@ -96,11 +92,9 @@ class BotanDB extends DB ...@@ -96,11 +92,9 @@ class BotanDB extends DB
$sth->bindParam(':short_url', $short_url); $sth->bindParam(':short_url', $short_url);
$sth->bindParam(':date', $created_at); $sth->bindParam(':date', $created_at);
$status = $sth->execute(); return $sth->execute();
} catch (Exception $e) { } catch (Exception $e) {
throw new TelegramException($e->getMessage()); throw new TelegramException($e->getMessage());
} }
return $status;
} }
} }
...@@ -35,7 +35,7 @@ class ChatsCommand extends AdminCommand ...@@ -35,7 +35,7 @@ class ChatsCommand extends AdminCommand
/** /**
* @var string * @var string
*/ */
protected $version = '1.0.2'; protected $version = '1.1.0';
/** /**
* @var bool * @var bool
...@@ -46,6 +46,7 @@ class ChatsCommand extends AdminCommand ...@@ -46,6 +46,7 @@ class ChatsCommand extends AdminCommand
* Command execute method * Command execute method
* *
* @return mixed * @return mixed
* @throws \Longman\TelegramBot\Exception\TelegramException
*/ */
public function execute() public function execute()
{ {
...@@ -61,7 +62,7 @@ class ChatsCommand extends AdminCommand ...@@ -61,7 +62,7 @@ class ChatsCommand extends AdminCommand
null, //'yyyy-mm-dd hh:mm:ss' date range from null, //'yyyy-mm-dd hh:mm:ss' date range from
null, //'yyyy-mm-dd hh:mm:ss' date range to null, //'yyyy-mm-dd hh:mm:ss' date range to
null, //Specific chat_id to select null, //Specific chat_id to select
($text === '' || $text == '*') ? null : $text //Text to search in user/group name ($text === '' || $text === '*') ? null : $text //Text to search in user/group name
); );
$user_chats = 0; $user_chats = 0;
...@@ -70,54 +71,56 @@ class ChatsCommand extends AdminCommand ...@@ -70,54 +71,56 @@ class ChatsCommand extends AdminCommand
if ($text === '') { if ($text === '') {
$text_back = ''; $text_back = '';
} elseif ($text == '*') { } elseif ($text === '*') {
$text_back = 'List of all bot chats:' . "\n"; $text_back = 'List of all bot chats:' . PHP_EOL;
} else { } else {
$text_back = 'Chat search results:' . "\n"; $text_back = 'Chat search results:' . PHP_EOL;
} }
foreach ($results as $result) { if (is_array($results)) {
//Initialize a chat object foreach ($results as $result) {
$result['id'] = $result['chat_id']; //Initialize a chat object
$chat = new Chat($result); $result['id'] = $result['chat_id'];
$chat = new Chat($result);
$whois = $chat->getId(); $whois = $chat->getId();
if ($this->telegram->getCommandObject('whois')) { if ($this->telegram->getCommandObject('whois')) {
// We can't use '-' in command because part of it will become unclickable // We can't use '-' in command because part of it will become unclickable
$whois = '/whois' . str_replace('-', 'g', $chat->getId()); $whois = '/whois' . str_replace('-', 'g', $chat->getId());
}
if ($chat->isPrivateChat()) {
if ($text != '') {
$text_back .= '- P ' . $chat->tryMention() . ' [' . $whois . ']' . "\n";
} }
++$user_chats; if ($chat->isPrivateChat()) {
} elseif ($chat->isSuperGroup()) { if ($text !== '') {
if ($text != '') { $text_back .= '- P ' . $chat->tryMention() . ' [' . $whois . ']' . PHP_EOL;
$text_back .= '- S ' . $chat->getTitle() . ' [' . $whois . ']' . "\n"; }
}
++$super_group_chats; ++$user_chats;
} elseif ($chat->isGroupChat()) { } elseif ($chat->isSuperGroup()) {
if ($text != '') { if ($text !== '') {
$text_back .= '- G ' . $chat->getTitle() . ' [' . $whois . ']' . "\n"; $text_back .= '- S ' . $chat->getTitle() . ' [' . $whois . ']' . PHP_EOL;
} }
++$super_group_chats;
} elseif ($chat->isGroupChat()) {
if ($text !== '') {
$text_back .= '- G ' . $chat->getTitle() . ' [' . $whois . ']' . PHP_EOL;
}
++$group_chats; ++$group_chats;
}
} }
} }
if (($user_chats + $group_chats + $super_group_chats) === 0) { if (($user_chats + $group_chats + $super_group_chats) === 0) {
$text_back = 'No chats found..'; $text_back = 'No chats found..';
} else { } else {
$text_back .= "\n" . 'Private Chats: ' . $user_chats; $text_back .= PHP_EOL . 'Private Chats: ' . $user_chats;
$text_back .= "\n" . 'Group: ' . $group_chats; $text_back .= PHP_EOL . 'Groups: ' . $group_chats;
$text_back .= "\n" . 'Super Group: ' . $super_group_chats; $text_back .= PHP_EOL . 'Super Groups: ' . $super_group_chats;
$text_back .= "\n" . 'Total: ' . ($user_chats + $group_chats + $super_group_chats); $text_back .= PHP_EOL . 'Total: ' . ($user_chats + $group_chats + $super_group_chats);
if ($text === '') { if ($text === '') {
$text_back .= "\n\n" . 'List all chats: /' . $this->name . ' *' . "\n" . 'Search for chats: /' . $this->name . ' <search string>'; $text_back .= PHP_EOL . PHP_EOL . 'List all chats: /' . $this->name . ' *' . PHP_EOL . 'Search for chats: /' . $this->name . ' <search string>';
} }
} }
......
...@@ -11,6 +11,8 @@ ...@@ -11,6 +11,8 @@
namespace Longman\TelegramBot\Commands\AdminCommands; namespace Longman\TelegramBot\Commands\AdminCommands;
use Longman\TelegramBot\Commands\AdminCommand; use Longman\TelegramBot\Commands\AdminCommand;
use Longman\TelegramBot\Entities\Message;
use Longman\TelegramBot\Entities\ServerResponse;
use Longman\TelegramBot\Request; use Longman\TelegramBot\Request;
/** /**
...@@ -36,7 +38,7 @@ class SendtoallCommand extends AdminCommand ...@@ -36,7 +38,7 @@ class SendtoallCommand extends AdminCommand
/** /**
* @var string * @var string
*/ */
protected $version = '1.2.1'; protected $version = '1.3.0';
/** /**
* @var bool * @var bool
...@@ -47,6 +49,7 @@ class SendtoallCommand extends AdminCommand ...@@ -47,6 +49,7 @@ class SendtoallCommand extends AdminCommand
* Execute command * Execute command
* *
* @return boolean * @return boolean
* @throws \Longman\TelegramBot\Exception\TelegramException
*/ */
public function execute() public function execute()
{ {
...@@ -68,18 +71,21 @@ class SendtoallCommand extends AdminCommand ...@@ -68,18 +71,21 @@ class SendtoallCommand extends AdminCommand
null //'yyyy-mm-dd hh:mm:ss' date range to null //'yyyy-mm-dd hh:mm:ss' date range to
); );
$tot = 0; $total = 0;
$fail = 0; $failed = 0;
$text = 'Message sent to:' . "\n"; $text = 'Message sent to:' . "\n";
/** @var ServerResponse $result */
foreach ($results as $result) { foreach ($results as $result) {
$status = ''; $name = '';
$type = ''; $type = '';
if ($result->isOk()) { if ($result->isOk()) {
$status = '✔️'; $status = '✔️';
$ServerResponse = $result->getResult(); /** @var Message $message */
$chat = $ServerResponse->getChat(); $message = $result->getResult();
$chat = $message->getChat();
if ($chat->isPrivateChat()) { if ($chat->isPrivateChat()) {
$name = $chat->getFirstName(); $name = $chat->getFirstName();
$type = 'user'; $type = 'user';
...@@ -89,15 +95,15 @@ class SendtoallCommand extends AdminCommand ...@@ -89,15 +95,15 @@ class SendtoallCommand extends AdminCommand
} }
} else { } else {
$status = '✖️'; $status = '✖️';
++$fail; ++$failed;
} }
++$tot; ++$total;
$text .= $tot . ') ' . $status . ' ' . $type . ' ' . $name . "\n"; $text .= $total . ') ' . $status . ' ' . $type . ' ' . $name . "\n";
} }
$text .= 'Delivered: ' . ($tot - $fail) . '/' . $tot . "\n"; $text .= 'Delivered: ' . ($total - $failed) . '/' . $total . "\n";
if ($tot === 0) { if ($total === 0) {
$text = 'No users or chats found..'; $text = 'No users or chats found..';
} }
} }
......
...@@ -15,6 +15,8 @@ namespace Longman\TelegramBot\Commands\AdminCommands; ...@@ -15,6 +15,8 @@ namespace Longman\TelegramBot\Commands\AdminCommands;
use Longman\TelegramBot\Commands\AdminCommand; use Longman\TelegramBot\Commands\AdminCommand;
use Longman\TelegramBot\DB; use Longman\TelegramBot\DB;
use Longman\TelegramBot\Entities\Chat; use Longman\TelegramBot\Entities\Chat;
use Longman\TelegramBot\Entities\PhotoSize;
use Longman\TelegramBot\Entities\UserProfilePhotos;
use Longman\TelegramBot\Request; use Longman\TelegramBot\Request;
/** /**
...@@ -40,7 +42,7 @@ class WhoisCommand extends AdminCommand ...@@ -40,7 +42,7 @@ class WhoisCommand extends AdminCommand
/** /**
* @var string * @var string
*/ */
protected $version = '1.1.0'; protected $version = '1.2.0';
/** /**
* @var bool * @var bool
...@@ -51,6 +53,7 @@ class WhoisCommand extends AdminCommand ...@@ -51,6 +53,7 @@ class WhoisCommand extends AdminCommand
* Command execute method * Command execute method
* *
* @return mixed * @return mixed
* @throws \Longman\TelegramBot\Exception\TelegramException
*/ */
public function execute() public function execute()
{ {
...@@ -71,7 +74,7 @@ class WhoisCommand extends AdminCommand ...@@ -71,7 +74,7 @@ class WhoisCommand extends AdminCommand
$text = substr($command, 5); $text = substr($command, 5);
//We need that '-' now, bring it back //We need that '-' now, bring it back
if ((substr($text, 0, 1) == 'g')) { if (strpos($text, 'g') === 0) {
$text = str_replace('g', '-', $text); $text = str_replace('g', '-', $text);
} }
} }
...@@ -79,10 +82,14 @@ class WhoisCommand extends AdminCommand ...@@ -79,10 +82,14 @@ class WhoisCommand extends AdminCommand
if ($text === '') { if ($text === '') {
$text = 'Provide the id to lookup: /whois <id>'; $text = 'Provide the id to lookup: /whois <id>';
} else { } else {
$user_id = $text; $user_id = $text;
$chat = null;
$created_at = null;
$updated_at = null;
$result = null;
if (is_numeric($text)) { if (is_numeric($text)) {
$result = DB::selectChats( $results = DB::selectChats(
true, //Select groups (group chat) true, //Select groups (group chat)
true, //Select supergroups (super group chat) true, //Select supergroups (super group chat)
true, //Select users (single chat) true, //Select users (single chat)
...@@ -91,7 +98,9 @@ class WhoisCommand extends AdminCommand ...@@ -91,7 +98,9 @@ class WhoisCommand extends AdminCommand
$user_id //Specific chat_id to select $user_id //Specific chat_id to select
); );
$result = $result[0]; if (!empty($results)) {
$result = reset($results);
}
} else { } else {
$results = DB::selectChats( $results = DB::selectChats(
true, //Select groups (group chat) true, //Select groups (group chat)
...@@ -103,8 +112,8 @@ class WhoisCommand extends AdminCommand ...@@ -103,8 +112,8 @@ class WhoisCommand extends AdminCommand
$text //Text to search in user/group name $text //Text to search in user/group name
); );
if (is_array($results) && count($results) == 1) { if (is_array($results) && count($results) === 1) {
$result = $results[0]; $result = reset($results);
} }
} }
...@@ -118,50 +127,53 @@ class WhoisCommand extends AdminCommand ...@@ -118,50 +127,53 @@ class WhoisCommand extends AdminCommand
$old_id = $result['old_id']; $old_id = $result['old_id'];
} }
if ($chat != null) { if ($chat !== null) {
if ($chat->isPrivateChat()) { if ($chat->isPrivateChat()) {
$text = 'User ID: ' . $user_id . "\n"; $text = 'User ID: ' . $user_id . PHP_EOL;
$text .= 'Name: ' . $chat->getFirstName() . ' ' . $chat->getLastName() . "\n"; $text .= 'Name: ' . $chat->getFirstName() . ' ' . $chat->getLastName() . PHP_EOL;
if ($chat->getUsername() != '') { $username = $chat->getUsername();
$text .= 'Username: @' . $chat->getUsername() . "\n"; if ($username !== null && $username !== '') {
$text .= 'Username: @' . $username . PHP_EOL;
} }
$text .= 'First time seen: ' . $created_at . "\n"; $text .= 'First time seen: ' . $created_at . PHP_EOL;
$text .= 'Last activity: ' . $updated_at . "\n"; $text .= 'Last activity: ' . $updated_at . PHP_EOL;
//Code from Whoami command //Code from Whoami command
$limit = 10; $limit = 10;
$offset = null; $offset = null;
$ServerResponse = Request::getUserProfilePhotos([ $response = Request::getUserProfilePhotos(
'user_id' => $user_id, [
'limit' => $limit, 'user_id' => $user_id,
'offset' => $offset, 'limit' => $limit,
]); 'offset' => $offset,
]
if ($ServerResponse->isOk()) { );
$UserProfilePhoto = $ServerResponse->getResult();
$totalcount = $UserProfilePhoto->getTotalCount(); if ($response->isOk()) {
} else { /** @var UserProfilePhotos $user_profile_photos */
$totalcount = 0; $user_profile_photos = $response->getResult();
}
if ($user_profile_photos->getTotalCount() > 0) {
if ($totalcount > 0) { $photos = $user_profile_photos->getPhotos();
$photos = $UserProfilePhoto->getPhotos();
$photo = $photos[0][2]; /** @var PhotoSize $photo */
$file_id = $photo->getFileId(); $photo = $photos[0][2];
$file_id = $photo->getFileId();
$data['photo'] = $file_id;
$data['caption'] = $text; $data['photo'] = $file_id;
$data['caption'] = $text;
return Request::sendPhoto($data);
return Request::sendPhoto($data);
}
} }
} elseif ($chat->isGroupChat()) { } elseif ($chat->isGroupChat()) {
$text = 'Chat ID: ' . $user_id . (!empty($old_id) ? ' (previously: ' . $old_id . ')' : '') . "\n"; $text = 'Chat ID: ' . $user_id . (!empty($old_id) ? ' (previously: ' . $old_id . ')' : '') . PHP_EOL;
$text .= 'Type: ' . ucfirst($chat->getType()) . "\n"; $text .= 'Type: ' . ucfirst($chat->getType()) . PHP_EOL;
$text .= 'Title: ' . $chat->getTitle() . "\n"; $text .= 'Title: ' . $chat->getTitle() . PHP_EOL;
$text .= 'First time added to group: ' . $created_at . "\n"; $text .= 'First time added to group: ' . $created_at . PHP_EOL;
$text .= 'Last activity: ' . $updated_at . "\n"; $text .= 'Last activity: ' . $updated_at . PHP_EOL;
} }
} elseif (is_array($results) && count($results) > 1) { } elseif (is_array($results) && count($results) > 1) {
$text = 'Multiple chats matched!'; $text = 'Multiple chats matched!';
...@@ -171,6 +183,7 @@ class WhoisCommand extends AdminCommand ...@@ -171,6 +183,7 @@ class WhoisCommand extends AdminCommand
} }
$data['text'] = $text; $data['text'] = $text;
return Request::sendMessage($data); return Request::sendMessage($data);
} }
} }
...@@ -20,7 +20,7 @@ abstract class Command ...@@ -20,7 +20,7 @@ abstract class Command
/** /**
* Telegram object * Telegram object
* *
* @var Telegram * @var \Longman\TelegramBot\Telegram
*/ */
protected $telegram; protected $telegram;
...@@ -90,7 +90,7 @@ abstract class Command ...@@ -90,7 +90,7 @@ abstract class Command
/** /**
* Constructor * Constructor
* *
* @param Telegram $telegram * @param \Longman\TelegramBot\Telegram $telegram
* @param \Longman\TelegramBot\Entities\Update $update * @param \Longman\TelegramBot\Entities\Update $update
*/ */
public function __construct(Telegram $telegram, Update $update = null) public function __construct(Telegram $telegram, Update $update = null)
...@@ -104,14 +104,16 @@ abstract class Command ...@@ -104,14 +104,16 @@ abstract class Command
* Set update object * Set update object
* *
* @param \Longman\TelegramBot\Entities\Update $update * @param \Longman\TelegramBot\Entities\Update $update
* @return Command *
* @return \Longman\TelegramBot\Commands\Command
*/ */
public function setUpdate(Update $update = null) public function setUpdate(Update $update = null)
{ {
if (!empty($update)) { if ($update !== null) {
$this->update = $update; $this->update = $update;
$this->message = $this->update->getMessage(); $this->message = $this->update->getMessage();
} }
return $this; return $this;
} }
...@@ -119,12 +121,14 @@ abstract class Command ...@@ -119,12 +121,14 @@ abstract class Command
* Pre-execute command * Pre-execute command
* *
* @return \Longman\TelegramBot\Entities\ServerResponse * @return \Longman\TelegramBot\Entities\ServerResponse
* @throws \Longman\TelegramBot\Exception\TelegramException
*/ */
public function preExecute() public function preExecute()
{ {
if ($this->need_mysql && !($this->telegram->isDbEnabled() && DB::isDbConnected())) { if ($this->need_mysql && !($this->telegram->isDbEnabled() && DB::isDbConnected())) {
return $this->executeNoDb(); return $this->executeNoDb();
} }
return $this->execute(); return $this->execute();
} }
...@@ -132,6 +136,7 @@ abstract class Command ...@@ -132,6 +136,7 @@ abstract class Command
* Execute command * Execute command
* *
* @return \Longman\TelegramBot\Entities\ServerResponse * @return \Longman\TelegramBot\Entities\ServerResponse
* @throws \Longman\TelegramBot\Exception\TelegramException
*/ */
abstract public function execute(); abstract public function execute();
...@@ -139,6 +144,7 @@ abstract class Command ...@@ -139,6 +144,7 @@ abstract class Command
* Execution if MySQL is required but not available * Execution if MySQL is required but not available
* *
* @return \Longman\TelegramBot\Entities\ServerResponse * @return \Longman\TelegramBot\Entities\ServerResponse
* @throws \Longman\TelegramBot\Exception\TelegramException
*/ */
public function executeNoDb() public function executeNoDb()
{ {
...@@ -182,7 +188,7 @@ abstract class Command ...@@ -182,7 +188,7 @@ abstract class Command
* *
* @param string|null $name * @param string|null $name
* *
* @return mixed * @return array|mixed|null
*/ */
public function getConfig($name = null) public function getConfig($name = null)
{ {
...@@ -192,13 +198,14 @@ abstract class Command ...@@ -192,13 +198,14 @@ abstract class Command
if (isset($this->config[$name])) { if (isset($this->config[$name])) {
return $this->config[$name]; return $this->config[$name];
} }
return null; return null;
} }
/** /**
* Get telegram object * Get telegram object
* *
* @return Telegram * @return \Longman\TelegramBot\Telegram
*/ */
public function getTelegram() public function getTelegram()
{ {
...@@ -248,7 +255,7 @@ abstract class Command ...@@ -248,7 +255,7 @@ abstract class Command
/** /**
* Check if command is enabled * Check if command is enabled
* *
* @return boolean * @return bool
*/ */
public function isEnabled() public function isEnabled()
{ {
......
...@@ -24,7 +24,7 @@ abstract class SystemCommand extends Command ...@@ -24,7 +24,7 @@ abstract class SystemCommand extends Command
*/ */
public function execute() public function execute()
{ {
//System command, return empty ServerResponse //System command, return empty ServerResponse by default
return Request::emptyResponse(); return Request::emptyResponse();
} }
} }
...@@ -31,12 +31,13 @@ class CallbackqueryCommand extends SystemCommand ...@@ -31,12 +31,13 @@ class CallbackqueryCommand extends SystemCommand
/** /**
* @var string * @var string
*/ */
protected $version = '1.0.0'; 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()
{ {
...@@ -45,15 +46,11 @@ class CallbackqueryCommand extends SystemCommand ...@@ -45,15 +46,11 @@ class CallbackqueryCommand extends SystemCommand
$callback_query_id = $callback_query->getId(); $callback_query_id = $callback_query->getId();
$callback_data = $callback_query->getData(); $callback_data = $callback_query->getData();
$data['callback_query_id'] = $callback_query_id; $data = [
'callback_query_id' => $callback_query_id,
if ($callback_data == 'thumb up') { 'text' => 'Hello World!',
$data['text'] = 'Hello World!'; 'show_alert' => $callback_data === 'thumb up',
$data['show_alert'] = true; ];
} else {
$data['text'] = 'Hello World!';
$data['show_alert'] = false;
}
return Request::answerCallbackQuery($data); return Request::answerCallbackQuery($data);
} }
......
...@@ -20,7 +20,7 @@ class ChannelchatcreatedCommand extends SystemCommand ...@@ -20,7 +20,7 @@ class ChannelchatcreatedCommand extends SystemCommand
/** /**
* @var string * @var string
*/ */
protected $name = 'Channelchatcreated'; protected $name = 'Channelchatcreated';
/** /**
* @var string * @var string
...@@ -30,11 +30,19 @@ class ChannelchatcreatedCommand extends SystemCommand ...@@ -30,11 +30,19 @@ class ChannelchatcreatedCommand extends SystemCommand
/** /**
* @var string * @var string
*/ */
protected $version = '1.0.1'; protected $version = '1.1.0';
/*public function execute() /**
* Command execute method
*
* @return mixed
* @throws \Longman\TelegramBot\Exception\TelegramException
*/
public function execute()
{ {
//$message = $this->getMessage(); //$message = $this->getMessage();
//$channel_chat_created = $message->getChannelChatCreated(); //$channel_chat_created = $message->getChannelChatCreated();
}*/
return parent::execute();
}
} }
...@@ -30,13 +30,21 @@ class ChoseninlineresultCommand extends SystemCommand ...@@ -30,13 +30,21 @@ class ChoseninlineresultCommand extends SystemCommand
/** /**
* @var string * @var string
*/ */
protected $version = '1.0.1'; protected $version = '1.1.0';
/*public function execute() /**
* Command execute method
*
* @return mixed
* @throws \Longman\TelegramBot\Exception\TelegramException
*/
public function execute()
{ {
//Information about chosen result is returned //Information about chosen result is returned
//$update = $this->getUpdate(); //$update = $this->getUpdate();
//$inline_query = $update->getChosenInlineResult(); //$inline_query = $update->getChosenInlineResult();
//$query = $inline_query->getQuery(); //$query = $inline_query->getQuery();
}*/
return parent::execute();
}
} }
...@@ -30,11 +30,19 @@ class DeletechatphotoCommand extends SystemCommand ...@@ -30,11 +30,19 @@ class DeletechatphotoCommand extends SystemCommand
/** /**
* @var string * @var string
*/ */
protected $version = '1.0.1'; protected $version = '1.1.0';
/*public function execute() /**
* Command execute method
*
* @return mixed
* @throws \Longman\TelegramBot\Exception\TelegramException
*/
public function execute()
{ {
//$message = $this->getMessage(); //$message = $this->getMessage();
//$delete_chat_photo = $message->getDeleteChatPhoto(); //$delete_chat_photo = $message->getDeleteChatPhoto();
}*/
return parent::execute();
}
} }
...@@ -30,11 +30,19 @@ class EditedmessageCommand extends SystemCommand ...@@ -30,11 +30,19 @@ class EditedmessageCommand extends SystemCommand
/** /**
* @var string * @var string
*/ */
protected $version = '1.0.0'; protected $version = '1.1.0';
/*public function execute() /**
* Command execute method
*
* @return mixed
* @throws \Longman\TelegramBot\Exception\TelegramException
*/
public function execute()
{ {
$update = $this->getUpdate(); //$update = $this->getUpdate();
$edited_message = $update->getEditedMessage(); //$edited_message = $update->getEditedMessage();
}*/
return parent::execute();
}
} }
...@@ -31,12 +31,13 @@ class GenericCommand extends SystemCommand ...@@ -31,12 +31,13 @@ class GenericCommand extends SystemCommand
/** /**
* @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()
{ {
...@@ -47,8 +48,9 @@ class GenericCommand extends SystemCommand ...@@ -47,8 +48,9 @@ class GenericCommand extends SystemCommand
$user_id = $message->getFrom()->getId(); $user_id = $message->getFrom()->getId();
$command = $message->getCommand(); $command = $message->getCommand();
if (in_array($user_id, $this->telegram->getAdminList()) && strtolower(substr($command, 0, 5)) == 'whois') { //If the user is and admin and the command is in the format "/whoisXYZ", call the /whois command
return $this->telegram->executeCommand('whois', $this->update); if (stripos($command, 'whois') === 0 && $this->telegram->isAdmin($user_id)) {
return $this->telegram->executeCommand('whois');
} }
$data = [ $data = [
......
...@@ -32,7 +32,7 @@ class GenericmessageCommand extends SystemCommand ...@@ -32,7 +32,7 @@ class GenericmessageCommand extends SystemCommand
/** /**
* @var string * @var string
*/ */
protected $version = '1.0.2'; protected $version = '1.1.0';
/** /**
* @var bool * @var bool
...@@ -54,6 +54,7 @@ class GenericmessageCommand extends SystemCommand ...@@ -54,6 +54,7 @@ class GenericmessageCommand extends SystemCommand
* Execute command * Execute command
* *
* @return \Longman\TelegramBot\Entities\ServerResponse * @return \Longman\TelegramBot\Entities\ServerResponse
* @throws \Longman\TelegramBot\Exception\TelegramException
*/ */
public function execute() public function execute()
{ {
...@@ -64,7 +65,7 @@ class GenericmessageCommand extends SystemCommand ...@@ -64,7 +65,7 @@ class GenericmessageCommand extends SystemCommand
); );
//Fetch conversation command if it exists and execute it //Fetch conversation command if it exists and execute it
if ($conversation->exists() && ($command = $conversation->getCommand())) { if ($conversation->exists() && ($command = $conversation->getCommand())) {
return $this->telegram->executeCommand($command, $this->update); return $this->telegram->executeCommand($command);
} }
return Request::emptyResponse(); return Request::emptyResponse();
......
...@@ -30,11 +30,19 @@ class GroupchatcreatedCommand extends SystemCommand ...@@ -30,11 +30,19 @@ class GroupchatcreatedCommand extends SystemCommand
/** /**
* @var string * @var string
*/ */
protected $version = '1.0.1'; protected $version = '1.1.0';
/*public function execute() /**
* Command execute method
*
* @return mixed
* @throws \Longman\TelegramBot\Exception\TelegramException
*/
public function execute()
{ {
//$message = $this->getMessage(); //$message = $this->getMessage();
//$group_chat_created = $message->getGroupChatCreated(); //$group_chat_created = $message->getGroupChatCreated();
}*/
return parent::execute();
}
} }
...@@ -33,12 +33,13 @@ class InlinequeryCommand extends SystemCommand ...@@ -33,12 +33,13 @@ class InlinequeryCommand extends SystemCommand
/** /**
* @var string * @var string
*/ */
protected $version = '1.0.2'; 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()
{ {
...@@ -55,19 +56,19 @@ class InlinequeryCommand extends SystemCommand ...@@ -55,19 +56,19 @@ class InlinequeryCommand extends SystemCommand
'id' => '001', 'id' => '001',
'title' => 'https://core.telegram.org/bots/api#answerinlinequery', 'title' => 'https://core.telegram.org/bots/api#answerinlinequery',
'description' => 'you enter: ' . $query, 'description' => 'you enter: ' . $query,
'input_message_content' => new InputTextMessageContent(['message_text' => ' ' . $query]) 'input_message_content' => new InputTextMessageContent(['message_text' => ' ' . $query]),
], ],
[ [
'id' => '002', 'id' => '002',
'title' => 'https://core.telegram.org/bots/api#answerinlinequery', 'title' => 'https://core.telegram.org/bots/api#answerinlinequery',
'description' => 'you enter: ' . $query, 'description' => 'you enter: ' . $query,
'input_message_content' => new InputTextMessageContent(['message_text' => ' ' . $query]) 'input_message_content' => new InputTextMessageContent(['message_text' => ' ' . $query]),
], ],
[ [
'id' => '003', 'id' => '003',
'title' => 'https://core.telegram.org/bots/api#answerinlinequery', 'title' => 'https://core.telegram.org/bots/api#answerinlinequery',
'description' => 'you enter: ' . $query, 'description' => 'you enter: ' . $query,
'input_message_content' => new InputTextMessageContent(['message_text' => ' ' . $query]) 'input_message_content' => new InputTextMessageContent(['message_text' => ' ' . $query]),
], ],
]; ];
......
...@@ -30,11 +30,19 @@ class LeftchatmemberCommand extends SystemCommand ...@@ -30,11 +30,19 @@ class LeftchatmemberCommand extends SystemCommand
/** /**
* @var string * @var string
*/ */
protected $version = '1.0.1'; protected $version = '1.1.0';
/*public function execute() /**
* Command execute method
*
* @return mixed
* @throws \Longman\TelegramBot\Exception\TelegramException
*/
public function execute()
{ {
//$message = $this->getMessage(); //$message = $this->getMessage();
//$member = $message->getLeftChatMember(); //$member = $message->getLeftChatMember();
}*/
return parent::execute();
}
} }
...@@ -30,11 +30,19 @@ class MigratefromchatidCommand extends SystemCommand ...@@ -30,11 +30,19 @@ class MigratefromchatidCommand extends SystemCommand
/** /**
* @var string * @var string
*/ */
protected $version = '1.0.1'; protected $version = '1.1.0';
/*public function execute() /**
* Command execute method
*
* @return mixed
* @throws \Longman\TelegramBot\Exception\TelegramException
*/
public function execute()
{ {
//$message = $this->getMessage(); //$message = $this->getMessage();
//$migrate_from_chat_id = $message->getMigrateFromChatId(); //$migrate_from_chat_id = $message->getMigrateFromChatId();
}*/
return parent::execute();
}
} }
...@@ -30,11 +30,19 @@ class MigratetochatidCommand extends SystemCommand ...@@ -30,11 +30,19 @@ class MigratetochatidCommand extends SystemCommand
/** /**
* @var string * @var string
*/ */
protected $version = '1.0.1'; protected $version = '1.1.0';
/*public function execute() /**
* Command execute method
*
* @return mixed
* @throws \Longman\TelegramBot\Exception\TelegramException
*/
public function execute()
{ {
//$message = $this->getMessage(); //$message = $this->getMessage();
//$migrate_to_chat_id = $message->getMigrateToChatId(); //$migrate_to_chat_id = $message->getMigrateToChatId();
}*/
return parent::execute();
}
} }
...@@ -31,10 +31,13 @@ class NewchatmemberCommand extends SystemCommand ...@@ -31,10 +31,13 @@ class NewchatmemberCommand extends SystemCommand
/** /**
* @var string * @var string
*/ */
protected $version = '1.0.1'; protected $version = '1.1.0';
/** /**
* Command execute method
*
* @return mixed * @return mixed
* @throws \Longman\TelegramBot\Exception\TelegramException
*/ */
public function execute() public function execute()
{ {
...@@ -42,10 +45,9 @@ class NewchatmemberCommand extends SystemCommand ...@@ -42,10 +45,9 @@ class NewchatmemberCommand extends SystemCommand
$chat_id = $message->getChat()->getId(); $chat_id = $message->getChat()->getId();
$member = $message->getNewChatMember(); $member = $message->getNewChatMember();
$text = 'Hi there!';
if ($message->botAddedInChat()) { if (!$message->botAddedInChat()) {
$text = 'Hi there!';
} else {
$text = 'Hi ' . $member->tryMention() . '!'; $text = 'Hi ' . $member->tryMention() . '!';
} }
......
...@@ -30,11 +30,19 @@ class NewchatphotoCommand extends SystemCommand ...@@ -30,11 +30,19 @@ class NewchatphotoCommand extends SystemCommand
/** /**
* @var string * @var string
*/ */
protected $version = '1.0.1'; protected $version = '1.1.0';
/*public function execute() /**
* Command execute method
*
* @return mixed
* @throws \Longman\TelegramBot\Exception\TelegramException
*/
public function execute()
{ {
//$message = $this->getMessage(); //$message = $this->getMessage();
//$new_chat_photo = $message->getNewChatPhoto(); //$new_chat_photo = $message->getNewChatPhoto();
}*/
return parent::execute();
}
} }
...@@ -30,11 +30,19 @@ class NewchattitleCommand extends SystemCommand ...@@ -30,11 +30,19 @@ class NewchattitleCommand extends SystemCommand
/** /**
* @var string * @var string
*/ */
protected $version = '1.0.1'; protected $version = '1.1.0';
/*public function execute() /**
* Command execute method
*
* @return mixed
* @throws \Longman\TelegramBot\Exception\TelegramException
*/
public function execute()
{ {
//$message = $this->getMessage(); //$message = $this->getMessage();
//$new_chat_title = $message->getNewChatTitle(); //$new_chat_title = $message->getNewChatTitle();
}*/
return parent::execute();
}
} }
...@@ -36,19 +36,20 @@ class StartCommand extends SystemCommand ...@@ -36,19 +36,20 @@ class StartCommand extends SystemCommand
/** /**
* @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();
$text = 'Hi there!' . "\n" . 'Type /help to see all commands!'; $text = 'Hi there!' . PHP_EOL . 'Type /help to see all commands!';
$data = [ $data = [
'chat_id' => $chat_id, 'chat_id' => $chat_id,
......
...@@ -30,11 +30,19 @@ class SupergroupchatcreatedCommand extends SystemCommand ...@@ -30,11 +30,19 @@ class SupergroupchatcreatedCommand extends SystemCommand
/** /**
* @var string * @var string
*/ */
protected $version = '1.0.1'; protected $version = '1.1.0';
/*public function execute() /**
* Command execute method
*
* @return mixed
* @throws \Longman\TelegramBot\Exception\TelegramException
*/
public function execute()
{ {
//$message = $this->getMessage(); //$message = $this->getMessage();
//$supergroup_chat_created = $message->getSuperGroupChatCreated(); //$supergroup_chat_created = $message->getSuperGroupChatCreated();
}*/
return parent::execute();
}
} }
...@@ -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);
} }
} }
This diff is collapsed.
...@@ -35,7 +35,7 @@ class KeyboardButton extends Entity ...@@ -35,7 +35,7 @@ class KeyboardButton extends Entity
* @param array $data * @param array $data
* @throws \Longman\TelegramBot\Exception\TelegramException * @throws \Longman\TelegramBot\Exception\TelegramException
*/ */
public function __construct($data = array()) public function __construct(array $data = [])
{ {
$this->text = isset($data['text']) ? $data['text'] : null; $this->text = isset($data['text']) ? $data['text'] : null;
if (empty($this->text)) { if (empty($this->text)) {
......
...@@ -40,27 +40,29 @@ class ReplyKeyboardMarkup extends Entity ...@@ -40,27 +40,29 @@ class ReplyKeyboardMarkup extends Entity
* ReplyKeyboardMarkup constructor. * ReplyKeyboardMarkup constructor.
* *
* @param array $data * @param array $data
*
* @throws \Longman\TelegramBot\Exception\TelegramException * @throws \Longman\TelegramBot\Exception\TelegramException
*/ */
public function __construct($data = array()) public function __construct(array $data = [])
{ {
if (isset($data['keyboard'])) { if (!isset($data['keyboard'])) {
if (is_array($data['keyboard'])) {
foreach ($data['keyboard'] as $item) {
if (!is_array($item)) {
throw new TelegramException('Keyboard subfield is not an array!');
}
}
$this->keyboard = $data['keyboard'];
} else {
throw new TelegramException('Keyboard field is not an array!');
}
} else {
throw new TelegramException('Keyboard field is empty!'); throw new TelegramException('Keyboard field is empty!');
} }
$this->resize_keyboard = isset($data['resize_keyboard']) ? $data['resize_keyboard'] : false; if (!is_array($data['keyboard'])) {
$this->one_time_keyboard = isset($data['one_time_keyboard']) ? $data['one_time_keyboard'] : false; throw new TelegramException('Keyboard field is not an array!');
$this->selective = isset($data['selective']) ? $data['selective'] : false; }
foreach ($data['keyboard'] as $item) {
if (!is_array($item)) {
throw new TelegramException('Keyboard subfield is not an array!');
}
}
$this->keyboard = $data['keyboard'];
//Set the object members from the passed data params
foreach (['resize_keyboard', 'one_time_keyboard', 'selective'] as $param) {
$this->$param = isset($data[$param]) ? (bool)$data[$param] : false;
}
} }
} }
...@@ -35,10 +35,12 @@ class ServerResponse extends Entity ...@@ -35,10 +35,12 @@ class ServerResponse extends Entity
* *
* @param array $data * @param array $data
* @param $bot_name * @param $bot_name
*
* @throws \Longman\TelegramBot\Exception\TelegramException
*/ */
public function __construct(array $data, $bot_name) public function __construct(array $data, $bot_name)
{ {
if (isset($data['ok']) && isset($data['result'])) { if (isset($data['ok'], $data['result'])) {
if (is_array($data['result'])) { if (is_array($data['result'])) {
if ($data['ok'] && !$this->isAssoc($data['result']) && !isset($data['result'][0]['user'])) { if ($data['ok'] && !$this->isAssoc($data['result']) && !isset($data['result'][0]['user'])) {
//Get Update //Get Update
...@@ -49,7 +51,7 @@ class ServerResponse extends Entity ...@@ -49,7 +51,7 @@ class ServerResponse extends Entity
//Response from getChatAdministrators //Response from getChatAdministrators
$this->result = []; $this->result = [];
foreach ($data['result'] as $user) { foreach ($data['result'] as $user) {
array_push($this->result, new ChatMember($user)); $this->result[] = new ChatMember($user);
} }
} elseif ($data['ok'] && $this->isAssoc($data['result'])) { } elseif ($data['ok'] && $this->isAssoc($data['result'])) {
if (isset($data['result']['total_count'])) { if (isset($data['result']['total_count'])) {
...@@ -79,15 +81,10 @@ class ServerResponse extends Entity ...@@ -79,15 +81,10 @@ class ServerResponse extends Entity
} else { } else {
if ($data['ok'] && $data['result'] === true) { if ($data['ok'] && $data['result'] === true) {
//Response from setWebhook set //Response from setWebhook set
$this->ok = $data['ok']; $this->ok = $data['ok'];
$this->result = true; $this->result = true;
$this->error_code = null; $this->error_code = null;
$this->description = isset($data['description']) ? $data['description'] : '';
if (isset($data['description'])) {
$this->description = $data['description'];
} else {
$this->description = '';
}
} elseif (is_numeric($data['result'])) { } elseif (is_numeric($data['result'])) {
//Response from getChatMembersCount //Response from getChatMembersCount
$this->result = $data['result']; $this->result = $data['result'];
...@@ -100,25 +97,10 @@ class ServerResponse extends Entity ...@@ -100,25 +97,10 @@ class ServerResponse extends Entity
} }
} else { } else {
//webHook not set //webHook not set
$this->ok = false; $this->ok = false;
$this->result = isset($data['result']) ? $data['result'] : null;
if (isset($data['result'])) { $this->error_code = isset($data['error_code']) ? $data['error_code'] : null;
$this->result = $data['result']; $this->description = isset($data['description']) ? $data['description'] : null;
} else {
$this->result = null;
}
if (isset($data['error_code'])) {
$this->error_code = $data['error_code'];
} else {
$this->error_code = null;
}
if (isset($data['description'])) {
$this->description = $data['description'];
} else {
$this->description = null;
}
//throw new TelegramException('ok(variable) is not set!'); //throw new TelegramException('ok(variable) is not set!');
} }
......
This diff is collapsed.
...@@ -18,6 +18,7 @@ use Longman\TelegramBot\Commands\Command; ...@@ -18,6 +18,7 @@ use Longman\TelegramBot\Commands\Command;
use Longman\TelegramBot\Entities\ServerResponse; use Longman\TelegramBot\Entities\ServerResponse;
use Longman\TelegramBot\Entities\Update; use Longman\TelegramBot\Entities\Update;
use Longman\TelegramBot\Exception\TelegramException; use Longman\TelegramBot\Exception\TelegramException;
use PDO;
use RecursiveDirectoryIterator; use RecursiveDirectoryIterator;
use RecursiveIteratorIterator; use RecursiveIteratorIterator;
use RegexIterator; use RegexIterator;
...@@ -125,8 +126,9 @@ class Telegram ...@@ -125,8 +126,9 @@ class Telegram
/** /**
* Telegram constructor. * Telegram constructor.
* *
* @param $api_key * @param string $api_key
* @param $bot_name * @param string $bot_name
*
* @throws \Longman\TelegramBot\Exception\TelegramException * @throws \Longman\TelegramBot\Exception\TelegramException
*/ */
public function __construct($api_key, $bot_name) public function __construct($api_key, $bot_name)
...@@ -160,26 +162,33 @@ class Telegram ...@@ -160,26 +162,33 @@ class Telegram
* @param string $encoding * @param string $encoding
* *
* @return \Longman\TelegramBot\Telegram * @return \Longman\TelegramBot\Telegram
* @throws \Longman\TelegramBot\Exception\TelegramException
*/ */
public function enableMySql(array $credential, $table_prefix = null, $encoding = 'utf8mb4') public function enableMySql(array $credential, $table_prefix = null, $encoding = 'utf8mb4')
{ {
$this->pdo = DB::initialize($credential, $this, $table_prefix, $encoding); $this->pdo = DB::initialize($credential, $this, $table_prefix, $encoding);
ConversationDB::initializeConversation(); ConversationDB::initializeConversation();
$this->mysql_enabled = true; $this->mysql_enabled = true;
return $this; return $this;
} }
/** /**
* Initialize Database external connection * Initialize Database external connection
* *
* @param /PDO $external_pdo_connection PDO database object * @param PDO $external_pdo_connection PDO database object
* @param string $table_prefix * @param string $table_prefix
*
* @return \Longman\TelegramBot\Telegram
* @throws \Longman\TelegramBot\Exception\TelegramException
*/ */
public function enableExternalMysql($external_pdo_connection, $table_prefix = null) public function enableExternalMySql($external_pdo_connection, $table_prefix = null)
{ {
$this->pdo = DB::externalInitialize($external_pdo_connection, $this, $table_prefix); $this->pdo = DB::externalInitialize($external_pdo_connection, $this, $table_prefix);
ConversationDB::initializeConversation(); ConversationDB::initializeConversation();
$this->mysql_enabled = true; $this->mysql_enabled = true;
return $this;
} }
/** /**
...@@ -236,7 +245,7 @@ class Telegram ...@@ -236,7 +245,7 @@ class Telegram
public function getCommandObject($command) public function getCommandObject($command)
{ {
$which = ['System']; $which = ['System'];
($this->isAdmin()) && $which[] = 'Admin'; $this->isAdmin() && $which[] = 'Admin';
$which[] = 'User'; $which[] = 'User';
foreach ($which as $auth) { foreach ($which as $auth) {
...@@ -259,6 +268,7 @@ class Telegram ...@@ -259,6 +268,7 @@ class Telegram
public function setCustomInput($input) public function setCustomInput($input)
{ {
$this->input = $input; $this->input = $input;
return $this; return $this;
} }
...@@ -289,6 +299,7 @@ class Telegram ...@@ -289,6 +299,7 @@ class Telegram
* @param int|null $timeout * @param int|null $timeout
* *
* @return \Longman\TelegramBot\Entities\ServerResponse * @return \Longman\TelegramBot\Entities\ServerResponse
* @throws \Longman\TelegramBot\Exception\TelegramException
*/ */
public function handleGetUpdates($limit = null, $timeout = null) public function handleGetUpdates($limit = null, $timeout = null)
{ {
...@@ -304,19 +315,23 @@ class Telegram ...@@ -304,19 +315,23 @@ class Telegram
//DB Query //DB Query
$last_update = DB::selectTelegramUpdate(1); $last_update = DB::selectTelegramUpdate(1);
$last_update = reset($last_update);
//As explained in the telegram bot api documentation //As explained in the telegram bot api documentation
$offset = (isset($last_update[0]['id'])) ? $last_update[0]['id'] + 1 : null; $offset = isset($last_update['id']) ? $last_update['id'] + 1 : null;
$response = Request::getUpdates([ $response = Request::getUpdates(
'offset' => $offset, [
'limit' => $limit, 'offset' => $offset,
'timeout' => $timeout, 'limit' => $limit,
]); 'timeout' => $timeout,
]
);
if ($response->isOk()) { if ($response->isOk()) {
//Process all updates //Process all updates
foreach ((array) $response->getResult() as $result) { /** @var Update $result */
foreach ((array)$response->getResult() as $result) {
$this->processUpdate($result); $this->processUpdate($result);
} }
} }
...@@ -338,6 +353,7 @@ class Telegram ...@@ -338,6 +353,7 @@ class Telegram
if (empty($this->input)) { if (empty($this->input)) {
throw new TelegramException('Input is empty!'); throw new TelegramException('Input is empty!');
} }
$post = json_decode($this->input, true); $post = json_decode($this->input, true);
if (empty($post)) { if (empty($post)) {
throw new TelegramException('Invalid JSON!'); throw new TelegramException('Invalid JSON!');
...@@ -368,6 +384,7 @@ class Telegram ...@@ -368,6 +384,7 @@ class Telegram
* @param \Longman\TelegramBot\Entities\Update $update * @param \Longman\TelegramBot\Entities\Update $update
* *
* @return \Longman\TelegramBot\Entities\ServerResponse * @return \Longman\TelegramBot\Entities\ServerResponse
* @throws \Longman\TelegramBot\Exception\TelegramException
*/ */
public function processUpdate(Update $update) public function processUpdate(Update $update)
{ {
...@@ -377,7 +394,7 @@ class Telegram ...@@ -377,7 +394,7 @@ class Telegram
$command = 'genericmessage'; $command = 'genericmessage';
$update_type = $this->update->getUpdateType(); $update_type = $this->update->getUpdateType();
if (in_array($update_type, ['inline_query', 'chosen_inline_result', 'callback_query', 'edited_message'])) { if (in_array($update_type, ['inline_query', 'chosen_inline_result', 'callback_query', 'edited_message'], true)) {
$command = $this->getCommandFromType($update_type); $command = $this->getCommandFromType($update_type);
} elseif ($update_type === 'message') { } elseif ($update_type === 'message') {
$message = $this->update->getMessage(); $message = $this->update->getMessage();
...@@ -403,7 +420,7 @@ class Telegram ...@@ -403,7 +420,7 @@ class Telegram
'new_chat_photo', 'new_chat_photo',
'new_chat_title', 'new_chat_title',
'supergroup_chat_created', 'supergroup_chat_created',
])) { ], true)) {
$command = $this->getCommandFromType($type); $command = $this->getCommandFromType($type);
} }
} }
...@@ -477,7 +494,7 @@ class Telegram ...@@ -477,7 +494,7 @@ class Telegram
*/ */
public function enableAdmin($admin_id) public function enableAdmin($admin_id)
{ {
if (is_int($admin_id) && $admin_id > 0 && !in_array($admin_id, $this->admins_list)) { if (is_int($admin_id) && $admin_id > 0 && !in_array($admin_id, $this->admins_list, true)) {
$this->admins_list[] = $admin_id; $this->admins_list[] = $admin_id;
} else { } else {
TelegramLog::error('Invalid value "' . $admin_id . '" for admin.'); TelegramLog::error('Invalid value "' . $admin_id . '" for admin.');
...@@ -524,20 +541,24 @@ class Telegram ...@@ -524,20 +541,24 @@ class Telegram
public function isAdmin($user_id = null) public function isAdmin($user_id = null)
{ {
if ($user_id === null && $this->update !== null) { if ($user_id === null && $this->update !== null) {
if (($message = $this->update->getMessage()) && ($from = $message->getFrom())) { //Try to figure out if the user is an admin
$user_id = $from->getId(); $update_methods = [
} elseif (($inline_query = $this->update->getInlineQuery()) && ($from = $inline_query->getFrom())) { 'getMessage',
$user_id = $from->getId(); 'getInlineQuery',
} elseif (($chosen_inline_result = $this->update->getChosenInlineResult()) && ($from = $chosen_inline_result->getFrom())) { 'getChosenInlineResult',
$user_id = $from->getId(); 'getCallbackQuery',
} elseif (($callback_query = $this->update->getCallbackQuery()) && ($from = $callback_query->getFrom())) { 'getEditedMessage',
$user_id = $from->getId(); ];
} elseif (($edited_message = $this->update->getEditedMessage()) && ($from = $edited_message->getFrom())) { foreach ($update_methods as $update_method) {
$user_id = $from->getId(); $object = call_user_func([$this->update, $update_method]);
if ($object !== null && $from = $object->getFrom()) {
$user_id = $from->getId();
break;
}
} }
} }
return ($user_id === null) ? false : in_array($user_id, $this->admins_list); return ($user_id === null) ? false : in_array($user_id, $this->admins_list, true);
} }
/** /**
...@@ -566,11 +587,11 @@ class Telegram ...@@ -566,11 +587,11 @@ class Telegram
{ {
if (!is_dir($path)) { if (!is_dir($path)) {
TelegramLog::error('Commands path "' . $path . '" does not exist.'); TelegramLog::error('Commands path "' . $path . '" does not exist.');
} elseif (!in_array($path, $this->commands_paths)) { } elseif (!in_array($path, $this->commands_paths, true)) {
if ($before) { if ($before) {
array_unshift($this->commands_paths, $path); array_unshift($this->commands_paths, $path);
} else { } else {
array_push($this->commands_paths, $path); $this->commands_paths[] = $path;
} }
} }
...@@ -588,7 +609,7 @@ class Telegram ...@@ -588,7 +609,7 @@ class Telegram
public function addCommandsPaths(array $paths, $before = true) public function addCommandsPaths(array $paths, $before = true)
{ {
foreach ($paths as $path) { foreach ($paths as $path) {
$this->addCommandsPath($path); $this->addCommandsPath($path, $before);
} }
return $this; return $this;
...@@ -604,6 +625,7 @@ class Telegram ...@@ -604,6 +625,7 @@ class Telegram
public function setUploadPath($path) public function setUploadPath($path)
{ {
$this->upload_path = $path; $this->upload_path = $path;
return $this; return $this;
} }
...@@ -627,6 +649,7 @@ class Telegram ...@@ -627,6 +649,7 @@ class Telegram
public function setDownloadPath($path) public function setDownloadPath($path)
{ {
$this->download_path = $path; $this->download_path = $path;
return $this; return $this;
} }
...@@ -655,6 +678,7 @@ class Telegram ...@@ -655,6 +678,7 @@ class Telegram
public function setCommandConfig($command, array $config) public function setCommandConfig($command, array $config)
{ {
$this->commands_config[$command] = $config; $this->commands_config[$command] = $config;
return $this; return $this;
} }
...@@ -777,12 +801,15 @@ class Telegram ...@@ -777,12 +801,15 @@ class Telegram
* Enable Botan.io integration * Enable Botan.io integration
* *
* @param $token * @param $token
*
* @return \Longman\TelegramBot\Telegram * @return \Longman\TelegramBot\Telegram
* @throws \Longman\TelegramBot\Exception\TelegramException
*/ */
public function enableBotan($token) public function enableBotan($token)
{ {
Botan::initializeBotan($token); Botan::initializeBotan($token);
$this->botan_enabled = true; $this->botan_enabled = true;
return $this; return $this;
} }
} }
...@@ -22,42 +22,42 @@ class TelegramLog ...@@ -22,42 +22,42 @@ class TelegramLog
* *
* @var \Monolog\Logger * @var \Monolog\Logger
*/ */
static protected $monolog = null; static protected $monolog;
/** /**
* Monolog instance for update * Monolog instance for update
* *
* @var \Monolog\Logger * @var \Monolog\Logger
*/ */
static protected $monolog_update = null; static protected $monolog_update;
/** /**
* Path for error log * Path for error log
* *
* @var string * @var string
*/ */
static protected $error_log_path = null; static protected $error_log_path;
/** /**
* Path for debug log * Path for debug log
* *
* @var string * @var string
*/ */
static protected $debug_log_path = null; static protected $debug_log_path;
/** /**
* Path for update log * Path for update log
* *
* @var string * @var string
*/ */
static protected $update_log_path = null; static protected $update_log_path;
/** /**
* Temporary stream handle for debug log * Temporary stream handle for debug log
* *
* @var null * @var null
*/ */
static protected $debug_log_temp_stream_handle = null; static protected $debug_log_temp_stream_handle;
/** /**
* Initialize * Initialize
...@@ -76,10 +76,10 @@ class TelegramLog ...@@ -76,10 +76,10 @@ class TelegramLog
self::$monolog = $external_monolog; self::$monolog = $external_monolog;
foreach (self::$monolog->getHandlers() as $handler) { foreach (self::$monolog->getHandlers() as $handler) {
if ($handler->getLevel() == 400) { if ($handler->getLevel() === 400) {
self::$error_log_path = true; self::$error_log_path = true;
} }
if ($handler->getLevel() == 100) { if ($handler->getLevel() === 100) {
self::$debug_log_path = true; self::$debug_log_path = true;
} }
} }
...@@ -87,6 +87,7 @@ class TelegramLog ...@@ -87,6 +87,7 @@ class TelegramLog
self::$monolog = new Logger('bot_log'); self::$monolog = new Logger('bot_log');
} }
} }
return self::$monolog; return self::$monolog;
} }
...@@ -97,6 +98,8 @@ class TelegramLog ...@@ -97,6 +98,8 @@ class TelegramLog
* *
* @return \Monolog\Logger * @return \Monolog\Logger
* @throws \Longman\TelegramBot\Exception\TelegramLogException * @throws \Longman\TelegramBot\Exception\TelegramLogException
* @throws \InvalidArgumentException
* @throws \Exception
*/ */
public static function initErrorLog($path) public static function initErrorLog($path)
{ {
...@@ -119,6 +122,8 @@ class TelegramLog ...@@ -119,6 +122,8 @@ class TelegramLog
* *
* @return \Monolog\Logger * @return \Monolog\Logger
* @throws \Longman\TelegramBot\Exception\TelegramLogException * @throws \Longman\TelegramBot\Exception\TelegramLogException
* @throws \InvalidArgumentException
* @throws \Exception
*/ */
public static function initDebugLog($path) public static function initDebugLog($path)
{ {
...@@ -148,6 +153,7 @@ class TelegramLog ...@@ -148,6 +153,7 @@ class TelegramLog
return false; return false;
} }
} }
return self::$debug_log_temp_stream_handle; return self::$debug_log_temp_stream_handle;
} }
...@@ -181,6 +187,8 @@ class TelegramLog ...@@ -181,6 +187,8 @@ class TelegramLog
* *
* @return \Monolog\Logger * @return \Monolog\Logger
* @throws \Longman\TelegramBot\Exception\TelegramLogException * @throws \Longman\TelegramBot\Exception\TelegramLogException
* @throws \InvalidArgumentException
* @throws \Exception
*/ */
public static function initUpdateLog($path) public static function initUpdateLog($path)
{ {
...@@ -200,6 +208,7 @@ class TelegramLog ...@@ -200,6 +208,7 @@ class TelegramLog
self::$monolog_update->pushHandler($update_handler); self::$monolog_update->pushHandler($update_handler);
} }
return self::$monolog; return self::$monolog;
} }
......
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