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
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';
/**#@-*/ /**#@-*/
/** /**
...@@ -37,18 +37,26 @@ class ImageCommand extends UserCommand ...@@ -37,18 +37,26 @@ class ImageCommand extends UserCommand
$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) { /**
* Return the path to a random image in the passed directory.
*
* @param string $dir
*
* @return string
*/
private function ShowRandomImage($dir)
{
$image_list = scandir($dir); $image_list = scandir($dir);
return $dir . "/" . $image_list[mt_rand(2, count($image_list) - 1)];
}
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';
/**#@-*/ /**#@-*/
/** /**
......
...@@ -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 //Example 2
$keyboard = [];
$keyboard[] = ['A']; $keyboard[] = ['A'];
$keyboard[] = ['B']; $keyboard[] = ['B'];
$keyboard[] = ['C']; $keyboard[] = ['C'];
$keyboards[] = $keyboard; $keyboards[] = $keyboard;
unset($keyboard);
//3 //Example 3
$keyboard = [];
$keyboard[] = ['A']; $keyboard[] = ['A'];
$keyboard[] = ['B']; $keyboard[] = ['B'];
$keyboard[] = ['C','D']; $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;
} }
...@@ -89,16 +89,17 @@ class Botan ...@@ -89,16 +89,17 @@ 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)
{ {
...@@ -54,12 +53,10 @@ class BotanDB extends DB ...@@ -54,12 +53,10 @@ class BotanDB extends DB
$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;
} }
/** /**
...@@ -69,9 +66,8 @@ class BotanDB extends DB ...@@ -69,9 +66,8 @@ class BotanDB extends DB
* @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)
{ {
...@@ -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,12 +71,13 @@ class ChatsCommand extends AdminCommand ...@@ -70,12 +71,13 @@ 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;
} }
if (is_array($results)) {
foreach ($results as $result) { foreach ($results as $result) {
//Initialize a chat object //Initialize a chat object
$result['id'] = $result['chat_id']; $result['id'] = $result['chat_id'];
...@@ -88,36 +90,37 @@ class ChatsCommand extends AdminCommand ...@@ -88,36 +90,37 @@ class ChatsCommand extends AdminCommand
} }
if ($chat->isPrivateChat()) { if ($chat->isPrivateChat()) {
if ($text != '') { if ($text !== '') {
$text_back .= '- P ' . $chat->tryMention() . ' [' . $whois . ']' . "\n"; $text_back .= '- P ' . $chat->tryMention() . ' [' . $whois . ']' . PHP_EOL;
} }
++$user_chats; ++$user_chats;
} elseif ($chat->isSuperGroup()) { } elseif ($chat->isSuperGroup()) {
if ($text != '') { if ($text !== '') {
$text_back .= '- S ' . $chat->getTitle() . ' [' . $whois . ']' . "\n"; $text_back .= '- S ' . $chat->getTitle() . ' [' . $whois . ']' . PHP_EOL;
} }
++$super_group_chats; ++$super_group_chats;
} elseif ($chat->isGroupChat()) { } elseif ($chat->isGroupChat()) {
if ($text != '') { if ($text !== '') {
$text_back .= '- G ' . $chat->getTitle() . ' [' . $whois . ']' . "\n"; $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..';
} }
} }
......
...@@ -38,7 +38,7 @@ class SendtochannelCommand extends AdminCommand ...@@ -38,7 +38,7 @@ class SendtochannelCommand extends AdminCommand
/** /**
* @var string * @var string
*/ */
protected $version = '0.1.4'; protected $version = '0.2.0';
/** /**
* @var bool * @var bool
...@@ -56,36 +56,43 @@ class SendtochannelCommand extends AdminCommand ...@@ -56,36 +56,43 @@ class SendtochannelCommand extends AdminCommand
* Command execute method * Command execute method
* *
* @return \Longman\TelegramBot\Entities\ServerResponse|mixed * @return \Longman\TelegramBot\Entities\ServerResponse|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();
$user_id = $message->getFrom()->getId(); $user_id = $message->getFrom()->getId();
$type = $message->getType(); $type = $message->getType();
// 'Cast' the command type into message this protect the machine state // 'Cast' the command type into message to protect the machine state
// if the commmad is recolled when the conversation is already started // if the commmad is recalled when the conversation is already started
$type = ($type == 'command') ? 'Message' : $type; $type = ($type === 'command') ? 'Message' : $type;
$text = trim($message->getText(true)); $text = trim($message->getText(true));
$text_yes_or_no = ($text === 'Yes' || $text === 'No');
$data = []; $data = [
$data['chat_id'] = $chat_id; 'chat_id' => $chat_id,
];
// Conversation // Conversation
$this->conversation = new Conversation($user_id, $chat_id, $this->getName()); $this->conversation = new Conversation($user_id, $chat_id, $this->getName());
$notes = &$this->conversation->notes;
$channels = (array)$this->getConfig('your_channel'); $channels = (array)$this->getConfig('your_channel');
if (!isset($this->conversation->notes['state'])) { if (isset($notes['state'])) {
$state = (count($channels) == 0) ? -1 : 0; $state = $notes['state'];
$this->conversation->notes['last_message_id'] = $message->getMessageId();
} else { } else {
$state = $this->conversation->notes['state']; $state = (count($channels) === 0) ? -1 : 0;
$notes['last_message_id'] = $message->getMessageId();
} }
switch ($state) { switch ($state) {
case -1: case -1:
// getConfig has not been configured asking for channel to administer // getConfig has not been configured asking for channel to administer
if ($type != 'Message' || $text === '') { if ($type !== 'Message' || $text === '') {
$this->conversation->notes['state'] = -1; $notes['state'] = -1;
$this->conversation->update(); $this->conversation->update();
$data['text'] = 'Insert the channel name: (@yourchannel)'; $data['text'] = 'Insert the channel name: (@yourchannel)';
...@@ -94,8 +101,8 @@ class SendtochannelCommand extends AdminCommand ...@@ -94,8 +101,8 @@ class SendtochannelCommand extends AdminCommand
break; break;
} }
$this->conversation->notes['channel'] = $text; $notes['channel'] = $text;
$this->conversation->notes['last_message_id'] = $message->getMessageId(); $notes['last_message_id'] = $message->getMessageId();
// Jump to state 1 // Jump to state 1
goto insert; goto insert;
...@@ -103,38 +110,35 @@ class SendtochannelCommand extends AdminCommand ...@@ -103,38 +110,35 @@ class SendtochannelCommand extends AdminCommand
default: default:
case 0: case 0:
// getConfig has been configured choose channel // getConfig has been configured choose channel
if ($type != 'Message' || !in_array($text, $channels)) { if ($type !== 'Message' || !in_array($text, $channels, true)) {
$this->conversation->notes['state'] = 0; $notes['state'] = 0;
$this->conversation->update(); $this->conversation->update();
$keyboard = []; $keyboard = [];
foreach ($channels as $channel) { foreach ($channels as $channel) {
$keyboard[] = [$channel]; $keyboard[] = [$channel];
} }
$reply_keyboard_markup = new ReplyKeyboardMarkup( $data['reply_markup'] = new ReplyKeyboardMarkup(
[ [
'keyboard' => $keyboard, 'keyboard' => $keyboard,
'resize_keyboard' => true, 'resize_keyboard' => true,
'one_time_keyboard' => true, 'one_time_keyboard' => true,
'selective' => true 'selective' => true,
] ]
); );
$data['reply_markup'] = $reply_keyboard_markup;
$data['text'] = 'Select a channel';
if ($type != 'Message' || !in_array($text, $channels)) {
$data['text'] = 'Select a channel from the keyboard:'; $data['text'] = 'Select a channel from the keyboard:';
}
$result = Request::sendMessage($data); $result = Request::sendMessage($data);
break; break;
} }
$this->conversation->notes['channel'] = $text; $notes['channel'] = $text;
$this->conversation->notes['last_message_id'] = $message->getMessageId(); $notes['last_message_id'] = $message->getMessageId();
// no break // no break
case 1: case 1:
insert: insert:
if ($this->conversation->notes['last_message_id'] == $message->getMessageId() || ($type == 'Message' && $text === '')) { if (($type === 'Message' && $text === '') || $notes['last_message_id'] === $message->getMessageId()) {
$this->conversation->notes['state'] = 1; $notes['state'] = 1;
$this->conversation->update(); $this->conversation->update();
$data['reply_markup'] = new ReplyKeyBoardHide(['selective' => true]); $data['reply_markup'] = new ReplyKeyBoardHide(['selective' => true]);
...@@ -142,45 +146,40 @@ class SendtochannelCommand extends AdminCommand ...@@ -142,45 +146,40 @@ class SendtochannelCommand extends AdminCommand
$result = Request::sendMessage($data); $result = Request::sendMessage($data);
break; break;
} }
$this->conversation->notes['last_message_id'] = $message->getMessageId(); $notes['last_message_id'] = $message->getMessageId();
$this->conversation->notes['message'] = $message->reflect(); $notes['message'] = $message->reflect();
$this->conversation->notes['message_type'] = $type; $notes['message_type'] = $type;
// no break // no break
case 2: case 2:
if ($this->conversation->notes['last_message_id'] == $message->getMessageId() || !($text == 'Yes' || $text == 'No')) { if (!$text_yes_or_no || $notes['last_message_id'] === $message->getMessageId()) {
$this->conversation->notes['state'] = 2; $notes['state'] = 2;
$this->conversation->update(); $this->conversation->update();
// Execute this just with object that allow caption // Execute this just with object that allow caption
if ($this->conversation->notes['message_type'] == 'Video' || $this->conversation->notes['message_type'] == 'Photo') { if ($notes['message_type'] === 'Video' || $notes['message_type'] === 'Photo') {
$keyboard = [['Yes', 'No']]; $data['reply_markup'] = new ReplyKeyboardMarkup(
$reply_keyboard_markup = new ReplyKeyboardMarkup(
[ [
'keyboard' => $keyboard, 'keyboard' => [['Yes', 'No']],
'resize_keyboard' => true, 'resize_keyboard' => true,
'one_time_keyboard' => true, 'one_time_keyboard' => true,
'selective' => true 'selective' => true,
] ]
); );
$data['reply_markup'] = $reply_keyboard_markup;
$data['text'] = 'Would you insert caption?'; $data['text'] = 'Would you like to insert a caption?';
if ($this->conversation->notes['last_message_id'] != $message->getMessageId() && !($text == 'Yes' || $text == 'No')) { if (!$text_yes_or_no && $notes['last_message_id'] !== $message->getMessageId()) {
$data['text'] = 'Would you insert a caption?' . "\n" . 'Type Yes or No'; $data['text'] .= PHP_EOL . 'Type Yes or No';
} }
$result = Request::sendMessage($data); $result = Request::sendMessage($data);
break; break;
} }
} }
$this->conversation->notes['set_caption'] = false; $notes['set_caption'] = ($text === 'Yes');
if ($text == 'Yes') { $notes['last_message_id'] = $message->getMessageId();
$this->conversation->notes['set_caption'] = true;
}
$this->conversation->notes['last_message_id'] = $message->getMessageId();
// no break // no break
case 3: case 3:
if (($this->conversation->notes['last_message_id'] == $message->getMessageId() || $type != 'Message') && $this->conversation->notes['set_caption']) { if ($notes['set_caption'] && ($notes['last_message_id'] === $message->getMessageId() || $type !== 'Message')) {
$this->conversation->notes['state'] = 3; $notes['state'] = 3;
$this->conversation->update(); $this->conversation->update();
$data['text'] = 'Insert caption:'; $data['text'] = 'Insert caption:';
...@@ -188,56 +187,52 @@ class SendtochannelCommand extends AdminCommand ...@@ -188,56 +187,52 @@ class SendtochannelCommand extends AdminCommand
$result = Request::sendMessage($data); $result = Request::sendMessage($data);
break; break;
} }
$this->conversation->notes['last_message_id'] = $message->getMessageId(); $notes['last_message_id'] = $message->getMessageId();
$this->conversation->notes['caption'] = $text; $notes['caption'] = $text;
// no break // no break
case 4: case 4:
if ($this->conversation->notes['last_message_id'] == $message->getMessageId() || !($text == 'Yes' || $text == 'No')) { if (!$text_yes_or_no || $notes['last_message_id'] === $message->getMessageId()) {
$this->conversation->notes['state'] = 4; $notes['state'] = 4;
$this->conversation->update(); $this->conversation->update();
$data['text'] = 'Message will look like this:'; $data['text'] = 'Message will look like this:';
$result = Request::sendMessage($data); $result = Request::sendMessage($data);
if ($this->conversation->notes['message_type'] != 'command') { if ($notes['message_type'] !== 'command') {
if ($this->conversation->notes['set_caption']) { if ($notes['set_caption']) {
$data['caption'] = $this->conversation->notes['caption']; $data['caption'] = $notes['caption'];
} }
$result = $this->sendBack(new Message($this->conversation->notes['message'], 'thisbot'), $data); $this->sendBack(new Message($notes['message'], $this->telegram->getBotName()), $data);
$data['text'] = 'Would you post it?'; $data['reply_markup'] = new ReplyKeyboardMarkup(
if ($this->conversation->notes['last_message_id'] != $message->getMessageId() && !($text == 'Yes' || $text == 'No')) {
$data['text'] = 'Would you post it?' . "\n" . 'Press Yes or No';
}
$keyboard = [['Yes', 'No']];
$reply_keyboard_markup = new ReplyKeyboardMarkup(
[ [
'keyboard' => $keyboard, 'keyboard' => [['Yes', 'No']],
'resize_keyboard' => true, 'resize_keyboard' => true,
'one_time_keyboard' => true, 'one_time_keyboard' => true,
'selective' => true 'selective' => true,
] ]
); );
$data['reply_markup'] = $reply_keyboard_markup;
$data['text'] = 'Would you like to post it?';
if (!$text_yes_or_no && $notes['last_message_id'] !== $message->getMessageId()) {
$data['text'] .= PHP_EOL . 'Type Yes or No';
}
$result = Request::sendMessage($data); $result = Request::sendMessage($data);
} }
break; break;
} }
$this->conversation->notes['post_message'] = false; $notes['post_message'] = ($text === 'Yes');
if ($text == 'Yes') { $notes['last_message_id'] = $message->getMessageId();
$this->conversation->notes['post_message'] = true;
}
$this->conversation->notes['last_message_id'] = $message->getMessageId();
// no break // no break
case 5: case 5:
$data['reply_markup'] = new ReplyKeyBoardHide(['selective' => true]); $data['reply_markup'] = new ReplyKeyBoardHide(['selective' => true]);
if ($this->conversation->notes['post_message']) { if ($notes['post_message']) {
$data['text'] = $this->publish( $data['text'] = $this->publish(
new Message($this->conversation->notes['message'], 'anystring'), new Message($notes['message'], $this->telegram->getBotName()),
$this->conversation->notes['channel'], $notes['channel'],
$this->conversation->notes['caption'] $notes['caption']
); );
} else { } else {
$data['text'] = 'Abort by user, message not sent..'; $data['text'] = 'Abort by user, message not sent..';
...@@ -246,31 +241,59 @@ class SendtochannelCommand extends AdminCommand ...@@ -246,31 +241,59 @@ class SendtochannelCommand extends AdminCommand
$this->conversation->stop(); $this->conversation->stop();
$result = Request::sendMessage($data); $result = Request::sendMessage($data);
} }
return $result; return $result;
} }
/** /**
* Execute without db * SendBack
* *
* @return mixed * Received a message, the bot can send a copy of it to another chat/channel.
* You don't have to care about the type of the message, the function detect it and use the proper
* REQUEST:: function to send it.
* $data include all the var that you need to send the message to the proper chat
*
* @todo This method will be moved to a higher level maybe in AdminCommand or Command
* @todo Looking for a more significant name
*
* @param \Longman\TelegramBot\Entities\Message $message
* @param array $data
*
* @return \Longman\TelegramBot\Entities\ServerResponse
* @throws \Longman\TelegramBot\Exception\TelegramException
*/ */
public function executeNoDb() protected function sendBack(Message $message, array $data)
{ {
$message = $this->getMessage(); $type = $message->getType();
$text = trim($message->getText(true)); $type = ($type === 'command') ? 'Message' : $type;
$chat_id = $message->getChat()->getId(); if ($type === 'Message') {
$data['text'] = $message->getText(true);
$data = []; } elseif ($type === 'Audio') {
$data['chat_id'] = $chat_id; $data['audio'] = $message->getAudio()->getFileId();
$data['duration'] = $message->getAudio()->getDuration();
if ($text === '') { $data['performer'] = $message->getAudio()->getPerformer();
$data['text'] = 'Usage: /sendtochannel <text>'; $data['title'] = $message->getAudio()->getTitle();
} else { } elseif ($type === 'Document') {
$channels = (array)$this->getConfig('your_channel'); $data['document'] = $message->getDocument()->getFileId();
$first_channel = $channels[0]; } elseif ($type === 'Photo') {
$data['text'] = $this->publish(new Message($message->reflect(), 'anystring'), $first_channel); $data['photo'] = $message->getPhoto()[0]->getFileId();
} elseif ($type === 'Sticker') {
$data['sticker'] = $message->getSticker()->getFileId();
} elseif ($type === 'Video') {
$data['video'] = $message->getVideo()->getFileId();
} elseif ($type === 'Voice') {
$data['voice'] = $message->getVoice()->getFileId();
} elseif ($type === 'Location') {
$data['latitude'] = $message->getLocation()->getLatitude();
$data['longitude'] = $message->getLocation()->getLongitude();
} }
return Request::sendMessage($data); $callback_path = 'Longman\TelegramBot\Request';
$callback_function = 'send' . $type;
if (!method_exists($callback_path, $callback_function)) {
throw new TelegramException('Methods: ' . $callback_function . ' not found in class Request.');
}
return call_user_func_array($callback_path . '::' . $callback_function, [$data]);
} }
/** /**
...@@ -281,6 +304,7 @@ class SendtochannelCommand extends AdminCommand ...@@ -281,6 +304,7 @@ class SendtochannelCommand extends AdminCommand
* @param string|null $caption * @param string|null $caption
* *
* @return string * @return string
* @throws \Longman\TelegramBot\Exception\TelegramException
*/ */
protected function publish(Message $message, $channel, $caption = null) protected function publish(Message $message, $channel, $caption = null)
{ {
...@@ -292,61 +316,42 @@ class SendtochannelCommand extends AdminCommand ...@@ -292,61 +316,42 @@ class SendtochannelCommand extends AdminCommand
if ($this->sendBack($message, $data)->isOk()) { if ($this->sendBack($message, $data)->isOk()) {
$response = 'Message sent successfully to: ' . $channel; $response = 'Message sent successfully to: ' . $channel;
} else { } else {
$response = 'Message not sent to: ' . $channel . "\n" . $response = 'Message not sent to: ' . $channel . PHP_EOL .
'- Does the channel exist?' . "\n" . '- Does the channel exist?' . PHP_EOL .
'- Is the bot an admin of the channel?'; '- Is the bot an admin of the channel?';
} }
return $response; return $response;
} }
/** /**
* SendBack * Execute without db
*
* Received a message, the bot can send a copy of it to another chat/channel.
* You don't have to care about the type of the message, the function detect it and use the proper
* REQUEST:: function to send it.
* $data include all the var that you need to send the message to the proper chat
* *
* @todo This method will be moved at an higher level maybe in AdminCommand or Command * @todo Why send just to the first found channel?
* @todo Looking for a more significative name
* *
* @param \Longman\TelegramBot\Entities\Message $message * @return mixed
* @param array $data
*
* @return \Longman\TelegramBot\Entities\ServerResponse
* @throws \Longman\TelegramBot\Exception\TelegramException * @throws \Longman\TelegramBot\Exception\TelegramException
*/ */
protected function sendBack(Message $message, array $data) public function executeNoDb()
{ {
$type = $message->getType(); $message = $this->getMessage();
$type = ($type == 'command') ? 'Message' : $type; $chat_id = $message->getChat()->getId();
if ($type == 'Message') { $text = trim($message->getText(true));
$data['text'] = $message->getText(true);
} elseif ($type == 'Audio') { $data = [
$data['audio'] = $message->getAudio()->getFileId(); 'chat_id' => $chat_id,
$data['duration'] = $message->getAudio()->getDuration(); 'text' => 'Usage: ' . $this->getUsage(),
$data['performer'] = $message->getAudio()->getPerformer(); ];
$data['title'] = $message->getAudio()->getTitle();
} elseif ($type == 'Document') { if ($text !== '') {
$data['document'] = $message->getDocument()->getFileId(); $channels = (array)$this->getConfig('your_channel');
} elseif ($type == 'Photo') { $first_channel = $channels[0];
$data['photo'] = $message->getPhoto()[0]->getFileId(); $data['text'] = $this->publish(
} elseif ($type == 'Sticker') { new Message($message->reflect(), $this->telegram->getBotName()),
$data['sticker'] = $message->getSticker()->getFileId(); $first_channel
} elseif ($type == 'Video') { );
$data['video'] = $message->getVideo()->getFileId();
} elseif ($type == 'Voice') {
$data['voice'] = $message->getVoice()->getFileId();
} elseif ($type == 'Location') {
$data['latitude'] = $message->getLocation()->getLatitude();
$data['longitude'] = $message->getLocation()->getLongitude();
}
$callback_path = 'Longman\TelegramBot\Request';
$callback_function = 'send' . $type;
if (!method_exists($callback_path, $callback_function)) {
throw new TelegramException('Methods: ' . $callback_function . ' not found in class Request.');
} }
return call_user_func_array($callback_path . '::' . $callback_function, [$data]); return Request::sendMessage($data);
} }
} }
...@@ -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);
} }
} }
...@@ -80,9 +83,13 @@ class WhoisCommand extends AdminCommand ...@@ -80,9 +83,13 @@ class WhoisCommand extends AdminCommand
$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,36 +127,38 @@ class WhoisCommand extends AdminCommand ...@@ -118,36 +127,38 @@ 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, 'user_id' => $user_id,
'limit' => $limit, 'limit' => $limit,
'offset' => $offset, 'offset' => $offset,
]); ]
);
if ($ServerResponse->isOk()) { if ($response->isOk()) {
$UserProfilePhoto = $ServerResponse->getResult(); /** @var UserProfilePhotos $user_profile_photos */
$totalcount = $UserProfilePhoto->getTotalCount(); $user_profile_photos = $response->getResult();
} else {
$totalcount = 0; if ($user_profile_photos->getTotalCount() > 0) {
} $photos = $user_profile_photos->getPhotos();
if ($totalcount > 0) { /** @var PhotoSize $photo */
$photos = $UserProfilePhoto->getPhotos();
$photo = $photos[0][2]; $photo = $photos[0][2];
$file_id = $photo->getFileId(); $file_id = $photo->getFileId();
...@@ -156,12 +167,13 @@ class WhoisCommand extends AdminCommand ...@@ -156,12 +167,13 @@ class WhoisCommand extends AdminCommand
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);
} }
......
...@@ -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();
if ($message->botAddedInChat()) {
$text = 'Hi there!'; $text = 'Hi there!';
} else {
if (!$message->botAddedInChat()) {
$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,19 +36,19 @@ class SlapCommand extends UserCommand ...@@ -36,19 +36,19 @@ 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();
......
...@@ -10,6 +10,7 @@ ...@@ -10,6 +10,7 @@
namespace Longman\TelegramBot\Commands\UserCommands; namespace Longman\TelegramBot\Commands\UserCommands;
use Longman\TelegramBot\Entities\PhotoSize;
use Longman\TelegramBot\Request; use Longman\TelegramBot\Request;
use Longman\TelegramBot\Conversation; use Longman\TelegramBot\Conversation;
use Longman\TelegramBot\Commands\UserCommand; use Longman\TelegramBot\Commands\UserCommand;
...@@ -40,7 +41,7 @@ class SurveyCommand extends UserCommand ...@@ -40,7 +41,7 @@ class SurveyCommand extends UserCommand
/** /**
* @var string * @var string
*/ */
protected $version = '0.2.0'; protected $version = '0.3.0';
/** /**
* @var bool * @var bool
...@@ -58,6 +59,7 @@ class SurveyCommand extends UserCommand ...@@ -58,6 +59,7 @@ class SurveyCommand extends UserCommand
* Command execute method * Command execute method
* *
* @return mixed * @return mixed
* @throws \Longman\TelegramBot\Exception\TelegramException
*/ */
public function execute() public function execute()
{ {
...@@ -65,186 +67,206 @@ class SurveyCommand extends UserCommand ...@@ -65,186 +67,206 @@ class SurveyCommand extends UserCommand
$chat = $message->getChat(); $chat = $message->getChat();
$user = $message->getFrom(); $user = $message->getFrom();
$text = $message->getText(true); $text = trim($message->getText(true));
$chat_id = $chat->getId(); $chat_id = $chat->getId();
$user_id = $user->getId(); $user_id = $user->getId();
//Preparing Respose //Preparing Response
$data = []; $data = [
'chat_id' => $chat_id,
];
if ($chat->isGroupChat() || $chat->isSuperGroup()) { if ($chat->isGroupChat() || $chat->isSuperGroup()) {
//reply to message id is applied by default //reply to message id is applied by default
//Force reply is applied by default to so can work with privacy on //Force reply is applied by default so it can work with privacy on
$data['reply_markup'] = new ForceReply(['selective' => true]); $data['reply_markup'] = new ForceReply(['selective' => true]);
} }
$data['chat_id'] = $chat_id;
//Conversation start //Conversation start
$this->conversation = new Conversation($user_id, $chat_id, $this->getName()); $this->conversation = new Conversation($user_id, $chat_id, $this->getName());
$notes = &$this->conversation->notes;
//cache data from the tracking session if any //cache data from the tracking session if any
if (!isset($this->conversation->notes['state'])) { $state = 0;
$state = '0'; if (isset($notes['state'])) {
} else { $state = $notes['state'];
$state = $this->conversation->notes['state'];
} }
//state machine $result = Request::emptyResponse();
//entrypoint of the machine state if given by the track
//Every time the step is achived the track is updated //State machine
//Entrypoint of the machine state if given by the track
//Every time a step is achieved the track is updated
switch ($state) { switch ($state) {
case 0: case 0:
if (empty($text)) { if ($text === '') {
$this->conversation->notes['state'] = 0; $notes['state'] = 0;
$this->conversation->update(); $this->conversation->update();
$data['text'] = 'Type your name:'; $data['text'] = 'Type your name:';
$data['reply_markup'] = new ReplyKeyBoardHide(['selective' => true]); $data['reply_markup'] = new ReplyKeyBoardHide(['selective' => true]);
$result = Request::sendMessage($data); $result = Request::sendMessage($data);
break; break;
} }
$this->conversation->notes['name'] = $text;
$notes['name'] = $text;
$text = ''; $text = '';
// no break // no break
case 1: case 1:
if (empty($text)) { if ($text === '') {
$this->conversation->notes['state'] = 1; $notes['state'] = 1;
$this->conversation->update(); $this->conversation->update();
$data['text'] = 'Type your surname:'; $data['text'] = 'Type your surname:';
$result = Request::sendMessage($data); $result = Request::sendMessage($data);
break; break;
} }
$this->conversation->notes['surname'] = $text;
++$state; $notes['surname'] = $text;
$text = ''; $text = '';
// no break // no break
case 2: case 2:
if (empty($text) || !is_numeric($text)) { if ($text === '' || !is_numeric($text)) {
$this->conversation->notes['state'] = 2; $notes['state'] = 2;
$this->conversation->update(); $this->conversation->update();
$data['text'] = 'Type your age:'; $data['text'] = 'Type your age:';
if (!empty($text) && !is_numeric($text)) { if ($text !== '') {
$data['text'] = 'Type your age, must be a number'; $data['text'] = 'Type your age, must be a number:';
} }
$result = Request::sendMessage($data); $result = Request::sendMessage($data);
break; break;
} }
$this->conversation->notes['age'] = $text;
$notes['age'] = $text;
$text = ''; $text = '';
// no break // no break
case 3: case 3:
if (empty($text) || !($text == 'M' || $text == 'F')) { if ($text === '' || !($text === 'M' || $text === 'F')) {
$this->conversation->notes['state'] = 3; $notes['state'] = 3;
$this->conversation->update(); $this->conversation->update();
$keyboard = [['M', 'F']]; $data['reply_markup'] = new ReplyKeyboardMarkup(
$reply_keyboard_markup = new ReplyKeyboardMarkup(
[ [
'keyboard' => $keyboard, 'keyboard' => [['M', 'F']],
'resize_keyboard' => true, 'resize_keyboard' => true,
'one_time_keyboard' => true, 'one_time_keyboard' => true,
'selective' => true 'selective' => true,
] ]
); );
$data['reply_markup'] = $reply_keyboard_markup;
$data['text'] = 'Select your gender:'; $data['text'] = 'Select your gender:';
if (!empty($text) && !($text == 'M' || $text == 'F')) { if ($text !== '') {
$data['text'] = 'Select your gender, choose a keyboard option:'; $data['text'] = 'Select your gender, choose a keyboard option:';
} }
$result = Request::sendMessage($data); $result = Request::sendMessage($data);
break; break;
} }
$this->conversation->notes['gender'] = $text; $notes['gender'] = $text;
$text = '';
// no break // no break
case 4: case 4:
if (is_null($message->getLocation())) { if ($message->getLocation() === null) {
$this->conversation->notes['state'] = 4; $notes['state'] = 4;
$this->conversation->update(); $this->conversation->update();
$data['reply_markup'] = new ReplyKeyboardMarkup( $data['reply_markup'] = new ReplyKeyboardMarkup(
[ [
'keyboard' => [ 'keyboard' => [
[ [
[ [
'text' => 'Share Location', 'text' => 'Share Location',
'request_location' => true 'request_location' => true,
],
], ],
]
], ],
'resize_keyboard' => true, 'resize_keyboard' => true,
'one_time_keyboard' => true, 'one_time_keyboard' => true,
'selective' => true, 'selective' => true,
] ]
); );
$data['text'] = 'Share your location:'; $data['text'] = 'Share your location:';
$result = Request::sendMessage($data); $result = Request::sendMessage($data);
break; break;
} }
$this->conversation->notes['longitude'] = $message->getLocation()->getLongitude(); $notes['longitude'] = $message->getLocation()->getLongitude();
$this->conversation->notes['latitude'] = $message->getLocation()->getLatitude(); $notes['latitude'] = $message->getLocation()->getLatitude();
// no break // no break
case 5: case 5:
if (is_null($message->getPhoto())) { if ($message->getPhoto() === null) {
$this->conversation->notes['state'] = 5; $notes['state'] = 5;
$this->conversation->update(); $this->conversation->update();
$data['text'] = 'Insert your picture:'; $data['text'] = 'Insert your picture:';
$data['reply_markup'] = new ReplyKeyBoardHide(['selective' => true]);
$result = Request::sendMessage($data); $result = Request::sendMessage($data);
break; break;
} }
$this->conversation->notes['photo_id'] = $message->getPhoto()[0]->getFileId();
/** @var PhotoSize $photo */
$photo = $message->getPhoto()[0];
$notes['photo_id'] = $photo->getFileId();
// no break // no break
case 6: case 6:
if (is_null($message->getContact())) { if ($message->getContact() === null) {
$this->conversation->notes['state'] = 6; $notes['state'] = 6;
$this->conversation->update(); $this->conversation->update();
$data['text'] = 'Share your contact information:';
$data['reply_markup'] = new ReplyKeyboardMarkup( $data['reply_markup'] = new ReplyKeyboardMarkup(
[ [
'keyboard' => [ 'keyboard' => [
[ [
[ [
'text' => 'Share Contact', 'text' => 'Share Contact',
'request_contact' => true 'request_contact' => true,
],
], ],
]
], ],
'resize_keyboard' => true, 'resize_keyboard' => true,
'one_time_keyboard' => true, 'one_time_keyboard' => true,
'selective' => true, 'selective' => true,
] ]
); );
$data['text'] = 'Share your contact information:';
$result = Request::sendMessage($data); $result = Request::sendMessage($data);
break; break;
} }
$this->conversation->notes['phone_number'] = $message->getContact()->getPhoneNumber();
$notes['phone_number'] = $message->getContact()->getPhoneNumber();
// no break // no break
case 7: case 7:
$this->conversation->update(); $this->conversation->update();
$out_text = '/Survey result:' . "\n"; $out_text = '/Survey result:' . PHP_EOL;
unset($this->conversation->notes['state']); unset($notes['state']);
foreach ($this->conversation->notes as $k => $v) { foreach ($notes as $k => $v) {
$out_text .= "\n" . ucfirst($k) . ': ' . $v; $out_text .= PHP_EOL . ucfirst($k) . ': ' . $v;
} }
$data['photo'] = $this->conversation->notes['photo_id']; $data['photo'] = $notes['photo_id'];
$data['reply_markup'] = new ReplyKeyBoardHide(['selective' => true]); $data['reply_markup'] = new ReplyKeyBoardHide(['selective' => true]);
$data['caption'] = $out_text; $data['caption'] = $out_text;
$this->conversation->stop(); $this->conversation->stop();
$result = Request::sendPhoto($data); $result = Request::sendPhoto($data);
break; break;
} }
return $result; return $result;
} }
} }
...@@ -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,60 +41,63 @@ class WhoamiCommand extends UserCommand ...@@ -39,60 +41,63 @@ 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);
$data = [
'chat_id' => $chat_id,
'reply_to_message_id' => $message_id,
];
//Send chat action //Send chat action
Request::sendChatAction(['chat_id' => $chat_id, 'action' => 'typing']); Request::sendChatAction([
'chat_id' => $chat_id,
'action' => 'typing',
]);
$caption = 'Your Id: ' . $user_id . "\n"; $caption = sprintf(
$caption .= 'Name: ' . $message->getFrom()->getFirstName() 'Your Id: %d' . PHP_EOL .
. ' ' . $message->getFrom()->getLastName() . "\n"; 'Name: %s %s' . PHP_EOL .
$caption .= 'Username: ' . $message->getFrom()->getUsername(); 'Username: %s',
$user_id,
$from->getFirstName(),
$from->getLastName(),
$from->getUsername()
);
//Fetch user profile photo //Fetch user profile photo
$limit = 10; $limit = 10;
$offset = null; $offset = null;
$ServerResponse = Request::getUserProfilePhotos([ $response = Request::getUserProfilePhotos(
[
'user_id' => $user_id, 'user_id' => $user_id,
'limit' => $limit, 'limit' => $limit,
'offset' => $offset, 'offset' => $offset,
]); ]
);
//Check if the request isOK if ($response->isOk()) {
if ($ServerResponse->isOk()) { /** @var UserProfilePhotos $user_profile_photos */
$UserProfilePhoto = $ServerResponse->getResult(); $user_profile_photos = $response->getResult();
$totalcount = $UserProfilePhoto->getTotalCount();
} else {
$totalcount = 0;
}
$data = [ if ($user_profile_photos->getTotalCount() > 0) {
'chat_id' => $chat_id, $photos = $user_profile_photos->getPhotos();
'reply_to_message_id' => $message_id,
];
if ($totalcount > 0) { /** @var PhotoSize $photo */
$photos = $UserProfilePhoto->getPhotos();
//I pick the latest photo with the hight definition
$photo = $photos[0][2]; $photo = $photos[0][2];
$file_id = $photo->getFileId(); $file_id = $photo->getFileId();
...@@ -101,19 +106,21 @@ class WhoamiCommand extends UserCommand ...@@ -101,19 +106,21 @@ class WhoamiCommand extends UserCommand
$result = Request::sendPhoto($data); $result = Request::sendPhoto($data);
//Download the image pictures //Download the photo after send message response to speedup response
//Download after send message response to speedup response $response2 = Request::getFile(['file_id' => $file_id]);
$file_id = $photo->getFileId(); if ($response2->isOk()) {
$ServerResponse = Request::getFile(['file_id' => $file_id]); /** @var File $photo_file */
if ($ServerResponse->isOk()) { $photo_file = $response2->getResult();
Request::downloadFile($ServerResponse->getResult()); Request::downloadFile($photo_file);
}
return $result;
}
} }
} else {
//No Photo just send text //No Photo just send text
$data['text'] = $caption; $data['text'] = $caption;
$result = Request::sendMessage($data);
}
return $result; return Request::sendMessage($data);
} }
} }
...@@ -16,6 +16,7 @@ use Longman\TelegramBot\Entities\Chat; ...@@ -16,6 +16,7 @@ use Longman\TelegramBot\Entities\Chat;
use Longman\TelegramBot\Entities\ChosenInlineResult; use Longman\TelegramBot\Entities\ChosenInlineResult;
use Longman\TelegramBot\Entities\InlineQuery; use Longman\TelegramBot\Entities\InlineQuery;
use Longman\TelegramBot\Entities\Message; use Longman\TelegramBot\Entities\Message;
use Longman\TelegramBot\Entities\ReplyToMessage;
use Longman\TelegramBot\Entities\Update; use Longman\TelegramBot\Entities\Update;
use Longman\TelegramBot\Entities\User; use Longman\TelegramBot\Entities\User;
use Longman\TelegramBot\Exception\TelegramException; use Longman\TelegramBot\Exception\TelegramException;
...@@ -87,7 +88,7 @@ class DB ...@@ -87,7 +88,7 @@ class DB
self::$mysql_credentials = $credentials; self::$mysql_credentials = $credentials;
self::$table_prefix = $table_prefix; self::$table_prefix = $table_prefix;
self::defineTable(); self::defineTables();
return self::$pdo; return self::$pdo;
} }
...@@ -104,9 +105,12 @@ class DB ...@@ -104,9 +105,12 @@ class DB
* @return PDO PDO database object * @return PDO PDO database object
* @throws \Longman\TelegramBot\Exception\TelegramException * @throws \Longman\TelegramBot\Exception\TelegramException
*/ */
public static function externalInitialize($external_pdo_connection, Telegram $telegram, $table_prefix = null) public static function externalInitialize(
{ $external_pdo_connection,
if (empty($external_pdo_connection)) { Telegram $telegram,
$table_prefix = null
) {
if ($external_pdo_connection === null) {
throw new TelegramException('MySQL external connection not provided!'); throw new TelegramException('MySQL external connection not provided!');
} }
...@@ -115,42 +119,32 @@ class DB ...@@ -115,42 +119,32 @@ class DB
self::$mysql_credentials = null; self::$mysql_credentials = null;
self::$table_prefix = $table_prefix; self::$table_prefix = $table_prefix;
self::defineTable(); self::defineTables();
return self::$pdo; return self::$pdo;
} }
/** /**
* Define all the table with the proper prefix * Define all the tables with the proper prefix
*/ */
protected static function defineTable() protected static function defineTables()
{ {
if (!defined('TB_TELEGRAM_UPDATE')) { $tables = [
define('TB_TELEGRAM_UPDATE', self::$table_prefix . 'telegram_update'); 'callback_query',
} 'chat',
if (!defined('TB_MESSAGE')) { 'chosen_inline_result',
define('TB_MESSAGE', self::$table_prefix . 'message'); 'edited_message',
} 'inline_query',
if (!defined('TB_EDITED_MESSAGE')) { 'message',
define('TB_EDITED_MESSAGE', self::$table_prefix . 'edited_message'); 'telegram_update',
} 'user',
if (!defined('TB_INLINE_QUERY')) { 'user_chat',
define('TB_INLINE_QUERY', self::$table_prefix . 'inline_query'); ];
} foreach ($tables as $table) {
if (!defined('TB_CHOSEN_INLINE_RESULT')) { $table_name = 'TB_' . strtoupper($table);
define('TB_CHOSEN_INLINE_RESULT', self::$table_prefix . 'chosen_inline_result'); if (!defined($table_name)) {
} define($table_name, self::$table_prefix . $table);
if (!defined('TB_CALLBACK_QUERY')) {
define('TB_CALLBACK_QUERY', self::$table_prefix . 'callback_query');
} }
if (!defined('TB_USER')) {
define('TB_USER', self::$table_prefix . 'user');
}
if (!defined('TB_CHAT')) {
define('TB_CHAT', self::$table_prefix . 'chat');
}
if (!defined('TB_USER_CHAT')) {
define('TB_USER_CHAT', self::$table_prefix . 'user_chat');
} }
} }
...@@ -161,11 +155,7 @@ class DB ...@@ -161,11 +155,7 @@ class DB
*/ */
public static function isDbConnected() public static function isDbConnected()
{ {
if (empty(self::$pdo)) { return self::$pdo !== null;
return false;
} else {
return true;
}
} }
/** /**
...@@ -183,22 +173,24 @@ class DB ...@@ -183,22 +173,24 @@ class DB
} }
try { try {
$query = 'SELECT `id` FROM `' . TB_TELEGRAM_UPDATE . '` '; $sql = '
$query .= 'ORDER BY `id` DESC'; SELECT `id`
FROM `' . TB_TELEGRAM_UPDATE . '`
ORDER BY `id` DESC
';
if (!is_null($limit)) { if ($limit !== null) {
$query .= ' LIMIT :limit '; $sql .= 'LIMIT :limit';
} }
$sth_select_telegram_update = self::$pdo->prepare($query); $sth = self::$pdo->prepare($sql);
$sth_select_telegram_update->bindParam(':limit', $limit, PDO::PARAM_INT); $sth->bindParam(':limit', $limit, PDO::PARAM_INT);
$sth_select_telegram_update->execute(); $sth->execute();
$results = $sth_select_telegram_update->fetchAll(PDO::FETCH_ASSOC);
return $sth->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) { } catch (PDOException $e) {
throw new TelegramException($e->getMessage()); throw new TelegramException($e->getMessage());
} }
return $results;
} }
/** /**
...@@ -216,41 +208,67 @@ class DB ...@@ -216,41 +208,67 @@ class DB
} }
try { try {
//message table $sql = '
$query = 'SELECT * FROM `' . TB_MESSAGE . '` '; SELECT *
$query .= 'WHERE ' . TB_MESSAGE . '.`update_id` != 0 '; FROM `' . TB_MESSAGE . '`
$query .= 'ORDER BY ' . TB_MESSAGE . '.`message_id` DESC'; WHERE `update_id` != 0
ORDER BY `message_id` DESC
';
if (!is_null($limit)) { if ($limit !== null) {
$query .= ' LIMIT :limit '; $sql .= 'LIMIT :limit';
} }
$sth = self::$pdo->prepare($query); $sth = self::$pdo->prepare($sql);
$sth->bindParam(':limit', $limit, PDO::PARAM_INT); $sth->bindParam(':limit', $limit, PDO::PARAM_INT);
$sth->execute(); $sth->execute();
$results = $sth->fetchAll(PDO::FETCH_ASSOC);
return $sth->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) { } catch (PDOException $e) {
throw new TelegramException($e->getMessage()); throw new TelegramException($e->getMessage());
} }
return $results;
} }
/** /**
* Convert from unix timestamp to timestamp * Convert from unix timestamp to timestamp
* *
* @param int $time Unix timestamp * @param int $time Unix timestamp (if null, current timestamp is used)
* *
* @return null|string Timestamp if a time has been passed, else null * @return string
*/ */
protected static function getTimestamp($time = null) protected static function getTimestamp($time = null)
{ {
if (is_null($time)) { if ($time === null) {
return date('Y-m-d H:i:s', time()); $time = time();
} }
return date('Y-m-d H:i:s', $time); return date('Y-m-d H:i:s', $time);
} }
/**
* Convert array of Entity items to a JSON array
*
* @todo Find a better way, as json_* functions are very heavy
*
* @param array|null $entities
* @param mixed $default
*
* @return mixed
*/
public static function entitiesArrayToJson($entities, $default = null)
{
if (!is_array($entities)) {
return $default;
}
//Convert each Entity item into an object based on its JSON reflection
$json_entities = array_map(function ($entity) {
return json_decode($entity, true);
}, $entities);
return json_encode($json_entities);
}
/** /**
* Insert entry to telegram_update table * Insert entry to telegram_update table
* *
...@@ -274,7 +292,7 @@ class DB ...@@ -274,7 +292,7 @@ class DB
$callback_query_id, $callback_query_id,
$edited_message_id $edited_message_id
) { ) {
if (is_null($message_id) && is_null($inline_query_id) && is_null($chosen_inline_result_id) && is_null($callback_query_id) && is_null($edited_message_id)) { if ($message_id === null && $inline_query_id === null && $chosen_inline_result_id === null && $callback_query_id === null && $edited_message_id === null) {
throw new TelegramException('message_id, inline_query_id, chosen_inline_result_id, callback_query_id, edited_message_id are all null'); throw new TelegramException('message_id, inline_query_id, chosen_inline_result_id, callback_query_id, edited_message_id are all null');
} }
...@@ -283,28 +301,22 @@ class DB ...@@ -283,28 +301,22 @@ class DB
} }
try { try {
$sth_insert_telegram_update = self::$pdo->prepare('INSERT IGNORE INTO `' . TB_TELEGRAM_UPDATE . '` $sth = self::$pdo->prepare('
( INSERT IGNORE INTO `' . TB_TELEGRAM_UPDATE . '`
`id`, `chat_id`, `message_id`, `inline_query_id`, `chosen_inline_result_id`, `callback_query_id`, `edited_message_id` (`id`, `chat_id`, `message_id`, `inline_query_id`, `chosen_inline_result_id`, `callback_query_id`, `edited_message_id`)
) VALUES
VALUES ( (:id, :chat_id, :message_id, :inline_query_id, :chosen_inline_result_id, :callback_query_id, :edited_message_id)
:id, :chat_id, :message_id, :inline_query_id, :chosen_inline_result_id, :callback_query_id, :edited_message_id
)
'); ');
$sth_insert_telegram_update->bindParam(':id', $id, PDO::PARAM_INT); $sth->bindParam(':id', $id, PDO::PARAM_INT);
$sth_insert_telegram_update->bindParam(':chat_id', $chat_id, PDO::PARAM_INT); $sth->bindParam(':chat_id', $chat_id, PDO::PARAM_INT);
$sth_insert_telegram_update->bindParam(':message_id', $message_id, PDO::PARAM_INT); $sth->bindParam(':message_id', $message_id, PDO::PARAM_INT);
$sth_insert_telegram_update->bindParam(':inline_query_id', $inline_query_id, PDO::PARAM_INT); $sth->bindParam(':inline_query_id', $inline_query_id, PDO::PARAM_INT);
$sth_insert_telegram_update->bindParam( $sth->bindParam(':chosen_inline_result_id', $chosen_inline_result_id, PDO::PARAM_INT);
':chosen_inline_result_id', $sth->bindParam(':callback_query_id', $callback_query_id, PDO::PARAM_INT);
$chosen_inline_result_id, $sth->bindParam(':edited_message_id', $edited_message_id, PDO::PARAM_INT);
PDO::PARAM_INT
);
$sth_insert_telegram_update->bindParam(':callback_query_id', $callback_query_id, PDO::PARAM_INT);
$sth_insert_telegram_update->bindParam(':edited_message_id', $edited_message_id, PDO::PARAM_INT);
return $sth_insert_telegram_update->execute(); return $sth->execute();
} catch (PDOException $e) { } catch (PDOException $e) {
throw new TelegramException($e->getMessage()); throw new TelegramException($e->getMessage());
} }
...@@ -332,44 +344,44 @@ class DB ...@@ -332,44 +344,44 @@ class DB
$last_name = $user->getLastName(); $last_name = $user->getLastName();
try { try {
$sth1 = self::$pdo->prepare('INSERT INTO `' . TB_USER . '` $sth = self::$pdo->prepare('
( INSERT INTO `' . TB_USER . '`
`id`, `username`, `first_name`, `last_name`, `created_at`, `updated_at` (`id`, `username`, `first_name`, `last_name`, `created_at`, `updated_at`)
) VALUES
VALUES ( (:id, :username, :first_name, :last_name, :date, :date)
:id, :username, :first_name, :last_name, :date, :date ON DUPLICATE KEY UPDATE
) `username` = :username,
ON DUPLICATE KEY UPDATE `username`=:username, `first_name`=:first_name, `first_name` = :first_name,
`last_name`=:last_name, `updated_at`=:date `last_name` = :last_name,
`updated_at` = :date
'); ');
$sth1->bindParam(':id', $user_id, PDO::PARAM_INT); $sth->bindParam(':id', $user_id, PDO::PARAM_INT);
$sth1->bindParam(':username', $username, PDO::PARAM_STR, 255); $sth->bindParam(':username', $username, PDO::PARAM_STR, 255);
$sth1->bindParam(':first_name', $first_name, PDO::PARAM_STR, 255); $sth->bindParam(':first_name', $first_name, PDO::PARAM_STR, 255);
$sth1->bindParam(':last_name', $last_name, PDO::PARAM_STR, 255); $sth->bindParam(':last_name', $last_name, PDO::PARAM_STR, 255);
$sth1->bindParam(':date', $date, PDO::PARAM_STR); $sth->bindParam(':date', $date, PDO::PARAM_STR);
$status = $sth1->execute(); $status = $sth->execute();
} catch (PDOException $e) { } catch (PDOException $e) {
throw new TelegramException($e->getMessage()); throw new TelegramException($e->getMessage());
} }
//insert also the relationship to the chat into user_chat table //insert also the relationship to the chat into user_chat table
if (!is_null($chat)) { if ($chat instanceof Chat) {
$chat_id = $chat->getId(); $chat_id = $chat->getId();
try { try {
$sth3 = self::$pdo->prepare('INSERT IGNORE INTO `' . TB_USER_CHAT . '` $sth = self::$pdo->prepare('
( INSERT IGNORE INTO `' . TB_USER_CHAT . '`
`user_id`, `chat_id` (`user_id`, `chat_id`)
) VALUES
VALUES ( (:user_id, :chat_id)
:user_id, :chat_id ');
)');
$sth3->bindParam(':user_id', $user_id, PDO::PARAM_INT); $sth->bindParam(':user_id', $user_id, PDO::PARAM_INT);
$sth3->bindParam(':chat_id', $chat_id, PDO::PARAM_INT); $sth->bindParam(':chat_id', $chat_id, PDO::PARAM_INT);
$status = $sth3->execute(); $status = $sth->execute();
} catch (PDOException $e) { } catch (PDOException $e) {
throw new TelegramException($e->getMessage()); throw new TelegramException($e->getMessage());
} }
...@@ -396,34 +408,35 @@ class DB ...@@ -396,34 +408,35 @@ class DB
$chat_id = $chat->getId(); $chat_id = $chat->getId();
$chat_title = $chat->getTitle(); $chat_title = $chat->getTitle();
$type = $chat->getType(); $chat_type = $chat->getType();
try { try {
$sth2 = self::$pdo->prepare('INSERT INTO `' . TB_CHAT . '` $sth = self::$pdo->prepare('
( INSERT INTO `' . TB_CHAT . '`
`id`, `type`, `title`, `created_at` ,`updated_at`, `old_id` (`id`, `type`, `title`, `created_at` ,`updated_at`, `old_id`)
) VALUES
VALUES ( (:id, :type, :title, :date, :date, :oldid)
:id, :type, :title, :date, :date, :oldid ON DUPLICATE KEY UPDATE
) `type` = :type,
ON DUPLICATE KEY UPDATE `type`=:type, `title`=:title, `updated_at`=:date `title` = :title,
`updated_at` = :date
'); ');
if ($migrate_to_chat_id) { if ($migrate_to_chat_id) {
$type = 'supergroup'; $chat_type = 'supergroup';
$sth2->bindParam(':id', $migrate_to_chat_id, PDO::PARAM_INT); $sth->bindParam(':id', $migrate_to_chat_id, PDO::PARAM_INT);
$sth2->bindParam(':oldid', $chat_id, PDO::PARAM_INT); $sth->bindParam(':oldid', $chat_id, PDO::PARAM_INT);
} else { } else {
$sth2->bindParam(':id', $chat_id, PDO::PARAM_INT); $sth->bindParam(':id', $chat_id, PDO::PARAM_INT);
$sth2->bindParam(':oldid', $migrate_to_chat_id, PDO::PARAM_INT); $sth->bindParam(':oldid', $migrate_to_chat_id, PDO::PARAM_INT);
} }
$sth2->bindParam(':type', $type, PDO::PARAM_INT); $sth->bindParam(':type', $chat_type, PDO::PARAM_INT);
$sth2->bindParam(':title', $chat_title, PDO::PARAM_STR, 255); $sth->bindParam(':title', $chat_title, PDO::PARAM_STR, 255);
$sth2->bindParam(':date', $date, PDO::PARAM_STR); $sth->bindParam(':date', $date, PDO::PARAM_STR);
return $sth2->execute(); return $sth->execute();
} catch (PDOException $e) { } catch (PDOException $e) {
throw new TelegramException($e->getMessage()); throw new TelegramException($e->getMessage());
} }
...@@ -437,30 +450,36 @@ class DB ...@@ -437,30 +450,36 @@ class DB
* @param \Longman\TelegramBot\Entities\Update $update * @param \Longman\TelegramBot\Entities\Update $update
* *
* @return bool * @return bool
* @throws \Longman\TelegramBot\Exception\TelegramException
*/ */
public static function insertRequest(Update $update) public static function insertRequest(Update $update)
{ {
$update_id = $update->getUpdateId(); $update_id = $update->getUpdateId();
if ($update->getUpdateType() == 'message') { $update_type = $update->getUpdateType();
if ($update_type === 'message') {
$message = $update->getMessage(); $message = $update->getMessage();
if (self::insertMessageRequest($message)) { if (self::insertMessageRequest($message)) {
$message_id = $message->getMessageId(); $message_id = $message->getMessageId();
$chat_id = $message->getChat()->getId(); $chat_id = $message->getChat()->getId();
return self::insertTelegramUpdate($update_id, $chat_id, $message_id, null, null, null, null); return self::insertTelegramUpdate($update_id, $chat_id, $message_id, null, null, null, null);
} }
} elseif ($update->getUpdateType() == 'inline_query') { } elseif ($update_type === 'inline_query') {
$inline_query = $update->getInlineQuery(); $inline_query = $update->getInlineQuery();
if (self::insertInlineQueryRequest($inline_query)) { if (self::insertInlineQueryRequest($inline_query)) {
$inline_query_id = $inline_query->getId(); $inline_query_id = $inline_query->getId();
return self::insertTelegramUpdate($update_id, null, null, $inline_query_id, null, null, null); return self::insertTelegramUpdate($update_id, null, null, $inline_query_id, null, null, null);
} }
} elseif ($update->getUpdateType() == 'chosen_inline_result') { } elseif ($update_type === 'chosen_inline_result') {
$chosen_inline_result = $update->getChosenInlineResult(); $chosen_inline_result = $update->getChosenInlineResult();
if (self::insertChosenInlineResultRequest($chosen_inline_result)) { if (self::insertChosenInlineResultRequest($chosen_inline_result)) {
$chosen_inline_result_local_id = self::$pdo->lastInsertId(); $chosen_inline_result_local_id = self::$pdo->lastInsertId();
return self::insertTelegramUpdate( return self::insertTelegramUpdate(
$update_id, $update_id,
null, null,
...@@ -471,19 +490,21 @@ class DB ...@@ -471,19 +490,21 @@ class DB
null null
); );
} }
} elseif ($update->getUpdateType() == 'callback_query') { } elseif ($update_type === 'callback_query') {
$callback_query = $update->getCallbackQuery(); $callback_query = $update->getCallbackQuery();
if (self::insertCallbackQueryRequest($callback_query)) { if (self::insertCallbackQueryRequest($callback_query)) {
$callback_query_id = $callback_query->getId(); $callback_query_id = $callback_query->getId();
return self::insertTelegramUpdate($update_id, null, null, null, null, $callback_query_id, null); return self::insertTelegramUpdate($update_id, null, null, null, null, $callback_query_id, null);
} }
} elseif ($update->getUpdateType() == 'edited_message') { } elseif ($update_type === 'edited_message') {
$edited_message = $update->getEditedMessage(); $edited_message = $update->getEditedMessage();
if (self::insertEditedMessageRequest($edited_message)) { if (self::insertEditedMessageRequest($edited_message)) {
$chat_id = $edited_message->getChat()->getId(); $chat_id = $edited_message->getChat()->getId();
$edited_message_local_id = self::$pdo->lastInsertId(); $edited_message_local_id = self::$pdo->lastInsertId();
return self::insertTelegramUpdate( return self::insertTelegramUpdate(
$update_id, $update_id,
$chat_id, $chat_id,
...@@ -514,21 +535,18 @@ class DB ...@@ -514,21 +535,18 @@ class DB
} }
try { try {
$mysql_query = 'INSERT IGNORE INTO `' . TB_INLINE_QUERY . '` $sth = self::$pdo->prepare('
( INSERT IGNORE INTO `' . TB_INLINE_QUERY . '`
`id`, `user_id`, `location`, `query`, `offset`, `created_at` (`id`, `user_id`, `location`, `query`, `offset`, `created_at`)
) VALUES
VALUES ( (:inline_query_id, :user_id, :location, :query, :param_offset, :created_at)
:inline_query_id, :user_id, :location, :query, :param_offset, :created_at ');
)';
$sth_insert_inline_query = self::$pdo->prepare($mysql_query);
$date = self::getTimestamp(time()); $date = self::getTimestamp();
$inline_query_id = $inline_query->getId(); $inline_query_id = $inline_query->getId();
$from = $inline_query->getFrom(); $from = $inline_query->getFrom();
$user_id = null; $user_id = null;
if (is_object($from)) { if ($from instanceof User) {
$user_id = $from->getId(); $user_id = $from->getId();
self::insertUser($from, $date); self::insertUser($from, $date);
} }
...@@ -537,14 +555,14 @@ class DB ...@@ -537,14 +555,14 @@ class DB
$query = $inline_query->getQuery(); $query = $inline_query->getQuery();
$offset = $inline_query->getOffset(); $offset = $inline_query->getOffset();
$sth_insert_inline_query->bindParam(':inline_query_id', $inline_query_id, PDO::PARAM_INT); $sth->bindParam(':inline_query_id', $inline_query_id, PDO::PARAM_INT);
$sth_insert_inline_query->bindParam(':user_id', $user_id, PDO::PARAM_INT); $sth->bindParam(':user_id', $user_id, PDO::PARAM_INT);
$sth_insert_inline_query->bindParam(':location', $location, PDO::PARAM_STR); $sth->bindParam(':location', $location, PDO::PARAM_STR);
$sth_insert_inline_query->bindParam(':query', $query, PDO::PARAM_STR); $sth->bindParam(':query', $query, PDO::PARAM_STR);
$sth_insert_inline_query->bindParam(':param_offset', $offset, PDO::PARAM_STR); $sth->bindParam(':param_offset', $offset, PDO::PARAM_STR);
$sth_insert_inline_query->bindParam(':created_at', $date, PDO::PARAM_STR); $sth->bindParam(':created_at', $date, PDO::PARAM_STR);
return $sth_insert_inline_query->execute(); return $sth->execute();
} catch (PDOException $e) { } catch (PDOException $e) {
throw new TelegramException($e->getMessage()); throw new TelegramException($e->getMessage());
} }
...@@ -565,21 +583,18 @@ class DB ...@@ -565,21 +583,18 @@ class DB
} }
try { try {
$mysql_query = 'INSERT INTO `' . TB_CHOSEN_INLINE_RESULT . '` $sth = self::$pdo->prepare('
( INSERT INTO `' . TB_CHOSEN_INLINE_RESULT . '`
`result_id`, `user_id`, `location`, `inline_message_id`, `query`, `created_at` (`result_id`, `user_id`, `location`, `inline_message_id`, `query`, `created_at`)
) VALUES
VALUES ( (:result_id, :user_id, :location, :inline_message_id, :query, :created_at)
:result_id, :user_id, :location, :inline_message_id, :query, :created_at ');
)';
$sth_insert_chosen_inline_result = self::$pdo->prepare($mysql_query);
$date = self::getTimestamp(time()); $date = self::getTimestamp();
$result_id = $chosen_inline_result->getResultId(); $result_id = $chosen_inline_result->getResultId();
$from = $chosen_inline_result->getFrom(); $from = $chosen_inline_result->getFrom();
$user_id = null; $user_id = null;
if (is_object($from)) { if ($from instanceof User) {
$user_id = $from->getId(); $user_id = $from->getId();
self::insertUser($from, $date); self::insertUser($from, $date);
} }
...@@ -588,14 +603,14 @@ class DB ...@@ -588,14 +603,14 @@ class DB
$inline_message_id = $chosen_inline_result->getInlineMessageId(); $inline_message_id = $chosen_inline_result->getInlineMessageId();
$query = $chosen_inline_result->getQuery(); $query = $chosen_inline_result->getQuery();
$sth_insert_chosen_inline_result->bindParam(':result_id', $result_id, PDO::PARAM_STR); $sth->bindParam(':result_id', $result_id, PDO::PARAM_STR);
$sth_insert_chosen_inline_result->bindParam(':user_id', $user_id, PDO::PARAM_INT); $sth->bindParam(':user_id', $user_id, PDO::PARAM_INT);
$sth_insert_chosen_inline_result->bindParam(':location', $location, PDO::PARAM_INT); $sth->bindParam(':location', $location, PDO::PARAM_INT);
$sth_insert_chosen_inline_result->bindParam(':inline_message_id', $inline_message_id, PDO::PARAM_STR); $sth->bindParam(':inline_message_id', $inline_message_id, PDO::PARAM_STR);
$sth_insert_chosen_inline_result->bindParam(':query', $query, PDO::PARAM_STR); $sth->bindParam(':query', $query, PDO::PARAM_STR);
$sth_insert_chosen_inline_result->bindParam(':created_at', $date, PDO::PARAM_STR); $sth->bindParam(':created_at', $date, PDO::PARAM_STR);
return $sth_insert_chosen_inline_result->execute(); return $sth->execute();
} catch (PDOException $e) { } catch (PDOException $e) {
throw new TelegramException($e->getMessage()); throw new TelegramException($e->getMessage());
} }
...@@ -616,22 +631,18 @@ class DB ...@@ -616,22 +631,18 @@ class DB
} }
try { try {
$mysql_query = 'INSERT IGNORE INTO `' . TB_CALLBACK_QUERY . '` $sth = self::$pdo->prepare('
( INSERT IGNORE INTO `' . TB_CALLBACK_QUERY . '`
`id`, `user_id`, `chat_id`, `message_id`, `inline_message_id`, `data`, `created_at` (`id`, `user_id`, `chat_id`, `message_id`, `inline_message_id`, `data`, `created_at`)
) VALUES
VALUES ( (:callback_query_id, :user_id, :chat_id, :message_id, :inline_message_id, :data, :created_at)
:callback_query_id, :user_id, :chat_id, :message_id, :inline_message_id, :data, :created_at ');
)';
$sth_insert_callback_query = self::$pdo->prepare($mysql_query);
$date = self::getTimestamp(time());
$date = self::getTimestamp();
$callback_query_id = $callback_query->getId(); $callback_query_id = $callback_query->getId();
$from = $callback_query->getFrom(); $from = $callback_query->getFrom();
$user_id = null; $user_id = null;
if (is_object($from)) { if ($from instanceof User) {
$user_id = $from->getId(); $user_id = $from->getId();
self::insertUser($from, $date); self::insertUser($from, $date);
} }
...@@ -639,15 +650,19 @@ class DB ...@@ -639,15 +650,19 @@ class DB
$message = $callback_query->getMessage(); $message = $callback_query->getMessage();
$chat_id = null; $chat_id = null;
$message_id = null; $message_id = null;
if ($message) { if ($message instanceof Message) {
$chat_id = $message->getChat()->getId(); $chat_id = $message->getChat()->getId();
$message_id = $message->getMessageId(); $message_id = $message->getMessageId();
$sth = self::$pdo->prepare('SELECT * FROM `' . TB_MESSAGE . '` $is_message = self::$pdo->query('
WHERE `id` = ' . $message_id . ' AND `chat_id` = ' . $chat_id . ' LIMIT 1'); SELECT *
$sth->execute(); FROM `' . TB_MESSAGE . '`
WHERE `id` = ' . $message_id . '
AND `chat_id` = ' . $chat_id . '
LIMIT 1
')->rowCount();
if ($sth->rowCount() > 0) { if ($is_message) {
self::insertEditedMessageRequest($message); self::insertEditedMessageRequest($message);
} else { } else {
self::insertMessageRequest($message); self::insertMessageRequest($message);
...@@ -657,15 +672,15 @@ class DB ...@@ -657,15 +672,15 @@ class DB
$inline_message_id = $callback_query->getInlineMessageId(); $inline_message_id = $callback_query->getInlineMessageId();
$data = $callback_query->getData(); $data = $callback_query->getData();
$sth_insert_callback_query->bindParam(':callback_query_id', $callback_query_id, PDO::PARAM_INT); $sth->bindParam(':callback_query_id', $callback_query_id, PDO::PARAM_INT);
$sth_insert_callback_query->bindParam(':user_id', $user_id, PDO::PARAM_INT); $sth->bindParam(':user_id', $user_id, PDO::PARAM_INT);
$sth_insert_callback_query->bindParam(':chat_id', $chat_id, PDO::PARAM_INT); $sth->bindParam(':chat_id', $chat_id, PDO::PARAM_INT);
$sth_insert_callback_query->bindParam(':message_id', $message_id, PDO::PARAM_INT); $sth->bindParam(':message_id', $message_id, PDO::PARAM_INT);
$sth_insert_callback_query->bindParam(':inline_message_id', $inline_message_id, PDO::PARAM_STR); $sth->bindParam(':inline_message_id', $inline_message_id, PDO::PARAM_STR);
$sth_insert_callback_query->bindParam(':data', $data, PDO::PARAM_STR); $sth->bindParam(':data', $data, PDO::PARAM_STR);
$sth_insert_callback_query->bindParam(':created_at', $date, PDO::PARAM_STR); $sth->bindParam(':created_at', $date, PDO::PARAM_STR);
return $sth_insert_callback_query->execute(); return $sth->execute();
} catch (PDOException $e) { } catch (PDOException $e) {
throw new TelegramException($e->getMessage()); throw new TelegramException($e->getMessage());
} }
...@@ -694,10 +709,10 @@ class DB ...@@ -694,10 +709,10 @@ class DB
$forward_from = $message->getForwardFrom(); $forward_from = $message->getForwardFrom();
$forward_from_chat = $message->getForwardFromChat(); $forward_from_chat = $message->getForwardFromChat();
$photo = $message->getPhoto(); $photo = self::entitiesArrayToJson($message->getPhoto(), '');
$entities = $message->getEntities(); $entities = self::entitiesArrayToJson($message->getEntities(), null);
$new_chat_member = $message->getNewChatMember(); $new_chat_member = $message->getNewChatMember();
$new_chat_photo = $message->getNewChatPhoto(); $new_chat_photo = self::entitiesArrayToJson($message->getNewChatPhoto(), '');
$left_chat_member = $message->getLeftChatMember(); $left_chat_member = $message->getLeftChatMember();
$migrate_to_chat_id = $message->getMigrateToChatId(); $migrate_to_chat_id = $message->getMigrateToChatId();
...@@ -708,31 +723,32 @@ class DB ...@@ -708,31 +723,32 @@ class DB
self::insertUser($from, $date, $chat); self::insertUser($from, $date, $chat);
//Insert the forwarded message user in users table //Insert the forwarded message user in users table
if (is_object($forward_from)) { if ($forward_from instanceof User) {
$forward_date = self::getTimestamp($message->getForwardDate()); $forward_date = self::getTimestamp($message->getForwardDate());
self::insertUser($forward_from, $forward_date); self::insertUser($forward_from, $forward_date);
$forward_from = $forward_from->getId(); $forward_from = $forward_from->getId();
} }
if (is_object($forward_from_chat)) { if ($forward_from_chat instanceof Chat) {
$forward_date = self::getTimestamp($message->getForwardDate()); $forward_date = self::getTimestamp($message->getForwardDate());
self::insertChat($forward_from_chat, $forward_date); self::insertChat($forward_from_chat, $forward_date);
$forward_from_chat = $forward_from_chat->getId(); $forward_from_chat = $forward_from_chat->getId();
} }
//New and left chat member //New and left chat member
if ($new_chat_member) { if ($new_chat_member instanceof User) {
//Insert the new chat user //Insert the new chat user
self::insertUser($new_chat_member, $date, $chat); self::insertUser($new_chat_member, $date, $chat);
$new_chat_member = $new_chat_member->getId(); $new_chat_member = $new_chat_member->getId();
} elseif ($left_chat_member) { } elseif ($left_chat_member instanceof User) {
//Insert the left chat user //Insert the left chat user
self::insertUser($left_chat_member, $date, $chat); self::insertUser($left_chat_member, $date, $chat);
$left_chat_member = $left_chat_member->getId(); $left_chat_member = $left_chat_member->getId();
} }
try { try {
$sth = self::$pdo->prepare('INSERT IGNORE INTO `' . TB_MESSAGE . '` $sth = self::$pdo->prepare('
INSERT IGNORE INTO `' . TB_MESSAGE . '`
( (
`id`, `user_id`, `chat_id`, `date`, `forward_from`, `forward_from_chat`, `id`, `user_id`, `chat_id`, `date`, `forward_from`, `forward_from_chat`,
`forward_date`, `reply_to_chat`, `reply_to_message`, `text`, `entities`, `audio`, `document`, `forward_date`, `reply_to_chat`, `reply_to_message`, `text`, `entities`, `audio`, `document`,
...@@ -741,8 +757,7 @@ class DB ...@@ -741,8 +757,7 @@ class DB
`new_chat_title`,`new_chat_photo`, `delete_chat_photo`, `group_chat_created`, `new_chat_title`,`new_chat_photo`, `delete_chat_photo`, `group_chat_created`,
`supergroup_chat_created`, `channel_chat_created`, `supergroup_chat_created`, `channel_chat_created`,
`migrate_from_chat_id`, `migrate_to_chat_id`, `pinned_message` `migrate_from_chat_id`, `migrate_to_chat_id`, `pinned_message`
) ) VALUES (
VALUES (
:message_id, :user_id, :chat_id, :date, :forward_from, :forward_from_chat, :message_id, :user_id, :chat_id, :date, :forward_from, :forward_from_chat,
:forward_date, :reply_to_chat, :reply_to_message, :text, :entities, :audio, :document, :forward_date, :reply_to_chat, :reply_to_message, :text, :entities, :audio, :document,
:photo, :sticker, :video, :voice, :caption, :contact, :photo, :sticker, :video, :voice, :caption, :contact,
...@@ -758,7 +773,7 @@ class DB ...@@ -758,7 +773,7 @@ class DB
$reply_to_message = $message->getReplyToMessage(); $reply_to_message = $message->getReplyToMessage();
$reply_to_message_id = null; $reply_to_message_id = null;
if (is_object($reply_to_message)) { if ($reply_to_message instanceof ReplyToMessage) {
$reply_to_message_id = $reply_to_message->getMessageId(); $reply_to_message_id = $reply_to_message->getMessageId();
// please notice that, as explained in the documentation, reply_to_message don't contain other // please notice that, as explained in the documentation, reply_to_message don't contain other
// reply_to_message field so recursion deep is 1 // reply_to_message field so recursion deep is 1
...@@ -792,40 +807,17 @@ class DB ...@@ -792,40 +807,17 @@ class DB
$sth->bindParam(':forward_from_chat', $forward_from_chat, PDO::PARAM_INT); $sth->bindParam(':forward_from_chat', $forward_from_chat, PDO::PARAM_INT);
$sth->bindParam(':forward_date', $forward_date, PDO::PARAM_STR); $sth->bindParam(':forward_date', $forward_date, PDO::PARAM_STR);
$reply_chat_id = null; $reply_to_chat_id = null;
if ($reply_to_message_id) { if ($reply_to_message_id) {
$reply_chat_id = $chat_id; $reply_to_chat_id = $chat_id;
}
$var = [];
if (is_array($entities)) {
foreach ($entities as $elm) {
$var[] = json_decode($elm, true);
}
$entities = json_encode($var);
} else {
$entities = null;
} }
$sth->bindParam(':reply_to_chat', $reply_chat_id, PDO::PARAM_INT); $sth->bindParam(':reply_to_chat', $reply_to_chat_id, PDO::PARAM_INT);
$sth->bindParam(':reply_to_message', $reply_to_message_id, PDO::PARAM_INT); $sth->bindParam(':reply_to_message', $reply_to_message_id, PDO::PARAM_INT);
$sth->bindParam(':text', $text, PDO::PARAM_STR); $sth->bindParam(':text', $text, PDO::PARAM_STR);
$sth->bindParam(':entities', $entities, PDO::PARAM_STR); $sth->bindParam(':entities', $entities, PDO::PARAM_STR);
$sth->bindParam(':audio', $audio, PDO::PARAM_STR); $sth->bindParam(':audio', $audio, PDO::PARAM_STR);
$sth->bindParam(':document', $document, PDO::PARAM_STR); $sth->bindParam(':document', $document, PDO::PARAM_STR);
$var = [];
if (is_array($photo)) {
foreach ($photo as $elm) {
$var[] = json_decode($elm, true);
}
$photo = json_encode($var);
} else {
$photo = '';
}
$sth->bindParam(':photo', $photo, PDO::PARAM_STR); $sth->bindParam(':photo', $photo, PDO::PARAM_STR);
$sth->bindParam(':sticker', $sticker, PDO::PARAM_STR); $sth->bindParam(':sticker', $sticker, PDO::PARAM_STR);
$sth->bindParam(':video', $video, PDO::PARAM_STR); $sth->bindParam(':video', $video, PDO::PARAM_STR);
...@@ -837,19 +829,6 @@ class DB ...@@ -837,19 +829,6 @@ class DB
$sth->bindParam(':new_chat_member', $new_chat_member, PDO::PARAM_INT); $sth->bindParam(':new_chat_member', $new_chat_member, PDO::PARAM_INT);
$sth->bindParam(':left_chat_member', $left_chat_member, PDO::PARAM_INT); $sth->bindParam(':left_chat_member', $left_chat_member, PDO::PARAM_INT);
$sth->bindParam(':new_chat_title', $new_chat_title, PDO::PARAM_STR); $sth->bindParam(':new_chat_title', $new_chat_title, PDO::PARAM_STR);
//Array of PhotoSize
$var = [];
if (is_array($new_chat_photo)) {
foreach ($new_chat_photo as $elm) {
$var[] = json_decode($elm, true);
}
$new_chat_photo = json_encode($var);
} else {
$new_chat_photo = '';
}
$sth->bindParam(':new_chat_photo', $new_chat_photo, PDO::PARAM_STR); $sth->bindParam(':new_chat_photo', $new_chat_photo, PDO::PARAM_STR);
$sth->bindParam(':delete_chat_photo', $delete_chat_photo, PDO::PARAM_STR); $sth->bindParam(':delete_chat_photo', $delete_chat_photo, PDO::PARAM_STR);
$sth->bindParam(':group_chat_created', $group_chat_created, PDO::PARAM_STR); $sth->bindParam(':group_chat_created', $group_chat_created, PDO::PARAM_STR);
...@@ -886,7 +865,7 @@ class DB ...@@ -886,7 +865,7 @@ class DB
$edit_date = self::getTimestamp($edited_message->getEditDate()); $edit_date = self::getTimestamp($edited_message->getEditDate());
$entities = $edited_message->getEntities(); $entities = self::entitiesArrayToJson($edited_message->getEntities(), null);
//Insert chat //Insert chat
self::insertChat($chat, $edit_date); self::insertChat($chat, $edit_date);
...@@ -895,13 +874,12 @@ class DB ...@@ -895,13 +874,12 @@ class DB
self::insertUser($from, $edit_date, $chat); self::insertUser($from, $edit_date, $chat);
try { try {
$sth = self::$pdo->prepare('INSERT INTO `' . TB_EDITED_MESSAGE . '` $sth = self::$pdo->prepare('
( INSERT IGNORE INTO `' . TB_EDITED_MESSAGE . '`
`chat_id`, `message_id`, `user_id`, `edit_date`, `text`, `entities`, `caption` (`chat_id`, `message_id`, `user_id`, `edit_date`, `text`, `entities`, `caption`)
) VALUES
VALUES ( (:chat_id, :message_id, :user_id, :date, :text, :entities, :caption)
:chat_id, :message_id, :user_id, :date, :text, :entities, :caption ');
)');
$message_id = $edited_message->getMessageId(); $message_id = $edited_message->getMessageId();
$from_id = $from->getId(); $from_id = $from->getId();
...@@ -913,18 +891,6 @@ class DB ...@@ -913,18 +891,6 @@ class DB
$sth->bindParam(':message_id', $message_id, PDO::PARAM_INT); $sth->bindParam(':message_id', $message_id, PDO::PARAM_INT);
$sth->bindParam(':user_id', $from_id, PDO::PARAM_INT); $sth->bindParam(':user_id', $from_id, PDO::PARAM_INT);
$sth->bindParam(':date', $edit_date, PDO::PARAM_STR); $sth->bindParam(':date', $edit_date, PDO::PARAM_STR);
$var = [];
if (is_array($entities)) {
foreach ($entities as $elm) {
$var[] = json_decode($elm, true);
}
$entities = json_encode($var);
} else {
$entities = null;
}
$sth->bindParam(':text', $text, PDO::PARAM_STR); $sth->bindParam(':text', $text, PDO::PARAM_STR);
$sth->bindParam(':entities', $entities, PDO::PARAM_STR); $sth->bindParam(':entities', $entities, PDO::PARAM_STR);
$sth->bindParam(':caption', $caption, PDO::PARAM_STR); $sth->bindParam(':caption', $caption, PDO::PARAM_STR);
...@@ -967,77 +933,68 @@ class DB ...@@ -967,77 +933,68 @@ class DB
} }
try { try {
$query = 'SELECT * , $query = '
SELECT * ,
' . TB_CHAT . '.`id` AS `chat_id`, ' . TB_CHAT . '.`id` AS `chat_id`,
' . TB_CHAT . '.`created_at` AS `chat_created_at`, ' . TB_CHAT . '.`created_at` AS `chat_created_at`,
' . TB_CHAT . '.`updated_at` AS `chat_updated_at` ' . TB_CHAT . '.`updated_at` AS `chat_updated_at`
' . ';
(($select_users) ? ', ' . TB_USER . '.`id` AS `user_id` FROM `' . TB_CHAT . '` LEFT JOIN `' . TB_USER . '` if ($select_users) {
ON ' . TB_CHAT . '.`id`=' . TB_USER . '.`id`' : 'FROM `' . TB_CHAT . '`'); $query .= '
, ' . TB_USER . '.`id` AS `user_id`
FROM `' . TB_CHAT . '`
LEFT JOIN `' . TB_USER . '`
ON ' . TB_CHAT . '.`id`=' . TB_USER . '.`id`
';
} else {
$query .= 'FROM `' . TB_CHAT . '`';
}
//Building parts of query //Building parts of query
$where = []; $where = [];
$tokens = []; $tokens = [];
if (!$select_groups || !$select_users || !$select_super_groups) { if (!$select_groups || !$select_users || !$select_super_groups) {
$chat_or_user = ''; $chat_or_user = [];
if ($select_groups) {
$chat_or_user .= TB_CHAT . '.`type` = "group"';
}
if ($select_super_groups) {
if (!empty($chat_or_user)) {
$chat_or_user .= ' OR ';
}
$chat_or_user .= TB_CHAT . '.`type` = "supergroup"';
}
if ($select_users) {
if (!empty($chat_or_user)) {
$chat_or_user .= ' OR ';
}
$chat_or_user .= TB_CHAT . '.`type` = "private"'; $select_groups && $chat_or_user[] = TB_CHAT . '.`type` = "group"';
} $select_super_groups && $chat_or_user[] = TB_CHAT . '.`type` = "supergroup"';
$select_users && $chat_or_user[] = TB_CHAT . '.`type` = "private"';
$where[] = '(' . $chat_or_user . ')'; $where[] = '(' . implode(' OR ', $chat_or_user) . ')';
} }
if (!is_null($date_from)) { if (null !== $date_from) {
$where[] = TB_CHAT . '.`updated_at` >= :date_from'; $where[] = TB_CHAT . '.`updated_at` >= :date_from';
$tokens[':date_from'] = $date_from; $tokens[':date_from'] = $date_from;
} }
if (!is_null($date_to)) { if (null !== $date_to) {
$where[] = TB_CHAT . '.`updated_at` <= :date_to'; $where[] = TB_CHAT . '.`updated_at` <= :date_to';
$tokens[':date_to'] = $date_to; $tokens[':date_to'] = $date_to;
} }
if (!is_null($chat_id)) { if (null !== $chat_id) {
$where[] = TB_CHAT . '.`id` = :chat_id'; $where[] = TB_CHAT . '.`id` = :chat_id';
$tokens[':chat_id'] = $chat_id; $tokens[':chat_id'] = $chat_id;
} }
if (!is_null($text)) { if (null !== $text) {
if ($select_users) { if ($select_users) {
$where[] = '(LOWER(' . TB_CHAT . '.`title`) LIKE :text OR LOWER(' . TB_USER . '.`first_name`) LIKE :text OR LOWER(' . TB_USER . '.`last_name`) LIKE :text OR LOWER(' . TB_USER . '.`username`) LIKE :text)'; $where[] = '(
LOWER(' . TB_CHAT . '.`title`) LIKE :text
OR LOWER(' . TB_USER . '.`first_name`) LIKE :text
OR LOWER(' . TB_USER . '.`last_name`) LIKE :text
OR LOWER(' . TB_USER . '.`username`) LIKE :text
)';
} else { } else {
$where[] = 'LOWER(' . TB_CHAT . '.`title`) LIKE :text'; $where[] = 'LOWER(' . TB_CHAT . '.`title`) LIKE :text';
} }
$tokens[':text'] = '%' . strtolower($text) . '%'; $tokens[':text'] = '%' . strtolower($text) . '%';
} }
$a = 0; if (!empty($where)) {
foreach ($where as $part) { $query .= ' WHERE ' . implode(' AND ', $where);
if ($a) {
$query .= ' AND ' . $part;
} else {
$query .= ' WHERE ' . $part;
++$a;
}
} }
$query .= ' ORDER BY ' . TB_CHAT . '.`updated_at` ASC'; $query .= ' ORDER BY ' . TB_CHAT . '.`updated_at` ASC';
...@@ -1045,11 +1002,9 @@ class DB ...@@ -1045,11 +1002,9 @@ class DB
$sth = self::$pdo->prepare($query); $sth = self::$pdo->prepare($query);
$sth->execute($tokens); $sth->execute($tokens);
$result = $sth->fetchAll(PDO::FETCH_ASSOC); return $sth->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) { } catch (PDOException $e) {
throw new TelegramException($e->getMessage()); throw new TelegramException($e->getMessage());
} }
return $result;
} }
} }
...@@ -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'])) { throw new TelegramException('Keyboard field is empty!');
}
if (!is_array($data['keyboard'])) {
throw new TelegramException('Keyboard field is not an array!');
}
foreach ($data['keyboard'] as $item) { foreach ($data['keyboard'] as $item) {
if (!is_array($item)) { if (!is_array($item)) {
throw new TelegramException('Keyboard subfield is not an array!'); throw new TelegramException('Keyboard subfield is not an array!');
} }
} }
$this->keyboard = $data['keyboard']; $this->keyboard = $data['keyboard'];
} else {
throw new TelegramException('Keyboard field is not an array!');
}
} else {
throw new TelegramException('Keyboard field is empty!');
}
$this->resize_keyboard = isset($data['resize_keyboard']) ? $data['resize_keyboard'] : false; //Set the object members from the passed data params
$this->one_time_keyboard = isset($data['one_time_keyboard']) ? $data['one_time_keyboard'] : false; foreach (['resize_keyboard', 'one_time_keyboard', 'selective'] as $param) {
$this->selective = isset($data['selective']) ? $data['selective'] : false; $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'])) {
...@@ -82,12 +84,7 @@ class ServerResponse extends Entity ...@@ -82,12 +84,7 @@ class ServerResponse extends Entity
$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'];
...@@ -101,24 +98,9 @@ class ServerResponse extends Entity ...@@ -101,24 +98,9 @@ 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!');
} }
......
...@@ -87,6 +87,7 @@ class Request ...@@ -87,6 +87,7 @@ class Request
* Initialize * Initialize
* *
* @param \Longman\TelegramBot\Telegram $telegram * @param \Longman\TelegramBot\Telegram $telegram
*
* @throws \Longman\TelegramBot\Exception\TelegramException * @throws \Longman\TelegramBot\Exception\TelegramException
*/ */
public static function initialize(Telegram $telegram) public static function initialize(Telegram $telegram)
...@@ -120,6 +121,7 @@ class Request ...@@ -120,6 +121,7 @@ class Request
} }
TelegramLog::update(self::$input); TelegramLog::update(self::$input);
return self::$input; return self::$input;
} }
...@@ -130,7 +132,7 @@ class Request ...@@ -130,7 +132,7 @@ class Request
* *
* @return array Fake response data * @return array Fake response data
*/ */
public static function generateGeneralFakeServerResponse(array $data = null) public static function generateGeneralFakeServerResponse(array $data = [])
{ {
//PARAM BINDED IN PHPUNIT TEST FOR TestServerResponse.php //PARAM BINDED IN PHPUNIT TEST FOR TestServerResponse.php
//Maybe this is not the best possible implementation //Maybe this is not the best possible implementation
...@@ -140,7 +142,7 @@ class Request ...@@ -140,7 +142,7 @@ class Request
$fake_response = ['ok' => true]; // :) $fake_response = ['ok' => true]; // :)
if (!isset($data)) { if ($data === []) {
$fake_response['result'] = true; $fake_response['result'] = true;
} }
...@@ -161,57 +163,60 @@ class Request ...@@ -161,57 +163,60 @@ class Request
return $fake_response; return $fake_response;
} }
/**
* Properly set up the request params
*
* If any item of the array is a resource, reformat it to a multipart request.
* Else, just return the passed data as form params.
*
* @param array $data
*
* @return array
*/
private static function setUpRequestParams(array $data)
{
$has_resource = false;
$multipart = [];
//Reformat data array in multipart way if it contains a resource
foreach ($data as $key => $item) {
$has_resource |= is_resource($item);
$multipart[] = ['name' => $key, 'contents' => $item];
}
if ($has_resource) {
return ['multipart' => $multipart];
}
return ['form_params' => $data];
}
/** /**
* Execute HTTP Request * Execute HTTP Request
* *
* @param string $action Action to execute * @param string $action Action to execute
* @param array|null $data Data to attach to the execution * @param array $data Data to attach to the execution
* *
* @return mixed Result of the HTTP Request * @return string Result of the HTTP Request
* @throws \Longman\TelegramBot\Exception\TelegramException * @throws \Longman\TelegramBot\Exception\TelegramException
*/ */
public static function execute($action, array $data = null) public static function execute($action, array $data = [])
{ {
$debug_handle = TelegramLog::getDebugLogTempStream();
//Fix so that the keyboard markup is a string, not an object //Fix so that the keyboard markup is a string, not an object
if (isset($data['reply_markup']) && !is_string($data['reply_markup'])) { if (isset($data['reply_markup'])) {
$data['reply_markup'] = (string) $data['reply_markup']; $data['reply_markup'] = (string)$data['reply_markup'];
} }
$request_params = ['debug' => $debug_handle]; $request_params = self::setUpRequestParams($data);
//Check for resources in data
$contains_resource = false;
foreach ($data as $item) {
if (is_resource($item)) {
$contains_resource = true;
break;
}
}
//Reformat data array in multipart way $debug_handle = TelegramLog::getDebugLogTempStream();
if ($contains_resource) { $request_params['debug'] = $debug_handle;
foreach ($data as $key => $item) {
$request_params['multipart'][] = array('name' => $key, 'contents' => $item);
}
} else {
$request_params['form_params'] = $data;
}
try { try {
$response = self::$client->post( $response = self::$client->post(
'/bot' . self::$telegram->getApiKey() . '/' . $action, '/bot' . self::$telegram->getApiKey() . '/' . $action,
$request_params $request_params
); );
} catch (RequestException $e) { $result = (string)$response->getBody();
throw new TelegramException($e->getMessage());
} finally {
//Logging verbose debug output
TelegramLog::endDebugLogTempStream("Verbose HTTP Request output:\n%s\n");
}
$result = $response->getBody();
//Logging getUpdates Update //Logging getUpdates Update
if ($action === 'getUpdates') { if ($action === 'getUpdates') {
...@@ -219,43 +224,49 @@ class Request ...@@ -219,43 +224,49 @@ class Request
} }
return $result; return $result;
} catch (RequestException $e) {
throw new TelegramException($e->getMessage());
} finally {
//Logging verbose debug output
TelegramLog::endDebugLogTempStream("Verbose HTTP Request output:\n%s\n");
}
} }
/** /**
* Download file * Download file
* *
* @param Entities\File $file * @param \Longman\TelegramBot\Entities\File $file
* *
* @return boolean * @return boolean
* @throws \Longman\TelegramBot\Exception\TelegramException * @throws \Longman\TelegramBot\Exception\TelegramException
*/ */
public static function downloadFile(File $file) public static function downloadFile(File $file)
{ {
$path = $file->getFilePath(); $tg_file_path = $file->getFilePath();
$file_path = self::$telegram->getDownloadPath() . '/' . $tg_file_path;
//Create the directory
$loc_path = self::$telegram->getDownloadPath() . '/' . $path;
$dirname = dirname($loc_path); $file_dir = dirname($file_path);
if (!is_dir($dirname) && !mkdir($dirname, 0755, true)) { //For safety reasons, first try to create the directory, then check that it exists.
throw new TelegramException('Directory ' . $dirname . ' can\'t be created'); //This is in case some other process has created the folder in the meantime.
if (!@mkdir($file_dir, 0755, true) && !is_dir($file_dir)) {
throw new TelegramException('Directory ' . $file_dir . ' can\'t be created');
} }
$debug_handle = TelegramLog::getDebugLogTempStream(); $debug_handle = TelegramLog::getDebugLogTempStream();
try { try {
$response = self::$client->get( self::$client->get(
'/file/bot' . self::$telegram->getApiKey() . '/' . $path, '/file/bot' . self::$telegram->getApiKey() . '/' . $tg_file_path,
['debug' => $debug_handle, 'sink' => $loc_path] ['debug' => $debug_handle, 'sink' => $file_path]
); );
return filesize($file_path) > 0;
} catch (RequestException $e) { } catch (RequestException $e) {
throw new TelegramException($e->getMessage()); throw new TelegramException($e->getMessage());
} finally { } finally {
//Logging verbose debug output //Logging verbose debug output
TelegramLog::endDebugLogTempStream("Verbose HTTP File Download Request output:\n%s\n"); TelegramLog::endDebugLogTempStream("Verbose HTTP File Download Request output:\n%s\n");
} }
return (filesize($loc_path) > 0);
} }
/** /**
...@@ -272,6 +283,7 @@ class Request ...@@ -272,6 +283,7 @@ class Request
if ($fp === false) { if ($fp === false) {
throw new TelegramException('Cannot open ' . $file . ' for reading'); throw new TelegramException('Cannot open ' . $file . ' for reading');
} }
return $fp; return $fp;
} }
...@@ -281,37 +293,83 @@ class Request ...@@ -281,37 +293,83 @@ class Request
* @todo Fake response doesn't need json encoding? * @todo Fake response doesn't need json encoding?
* *
* @param string $action * @param string $action
* @param array|null $data * @param array $data
* *
* @return \Longman\TelegramBot\Entities\ServerResponse * @return \Longman\TelegramBot\Entities\ServerResponse
* @throws \Longman\TelegramBot\Exception\TelegramException * @throws \Longman\TelegramBot\Exception\TelegramException
*/ */
public static function send($action, array $data = null) public static function send($action, array $data = [])
{ {
if (!in_array($action, self::$actions)) { self::ensureValidAction($action);
throw new TelegramException('The action ' . $action . ' doesn\'t exist!');
}
$bot_name = self::$telegram->getBotName(); $bot_name = self::$telegram->getBotName();
if (defined('PHPUNIT_TESTSUITE')) { if (defined('PHPUNIT_TESTSUITE')) {
$fake_response = self::generateGeneralFakeServerResponse($data); $fake_response = self::generateGeneralFakeServerResponse($data);
return new ServerResponse($fake_response, $bot_name); return new ServerResponse($fake_response, $bot_name);
} }
self::ensureNonEmptyData($data);
$response = json_decode(self::execute($action, $data), true); $response = json_decode(self::execute($action, $data), true);
if (is_null($response)) { if (null === $response) {
throw new TelegramException('Telegram returned an invalid response! Please your bot name and api token.'); throw new TelegramException('Telegram returned an invalid response! Please review your bot name and API key.');
} }
return new ServerResponse($response, $bot_name); return new ServerResponse($response, $bot_name);
} }
/**
* Make sure the data isn't empty, else throw an exception
*
* @param array $data
*
* @throws \Longman\TelegramBot\Exception\TelegramException
*/
private static function ensureNonEmptyData(array $data)
{
if (count($data) === 0) {
throw new TelegramException('Data is empty!');
}
}
/**
* Make sure the action is valid, else throw an exception
*
* @param string $action
*
* @throws \Longman\TelegramBot\Exception\TelegramException
*/
private static function ensureValidAction($action)
{
if (!in_array($action, self::$actions, true)) {
throw new TelegramException('The action " . $action . " doesn\'t exist!');
}
}
/**
* Assign an encoded file to a data array
*
* @param array $data
* @param string $field
* @param string $file
*
* @throws \Longman\TelegramBot\Exception\TelegramException
*/
private static function assignEncodedFile(&$data, $field, $file)
{
if ($file !== null && $file !== '') {
$data[$field] = self::encodeFile($file);
}
}
/** /**
* Get me * Get me
* *
* @return mixed * @return mixed
* @throws \Longman\TelegramBot\Exception\TelegramException
*/ */
public static function getMe() public static function getMe()
{ {
...@@ -323,8 +381,6 @@ class Request ...@@ -323,8 +381,6 @@ class Request
/** /**
* Send message * Send message
* *
* @todo Could do with some cleaner recursion
*
* @param array $data * @param array $data
* *
* @return mixed * @return mixed
...@@ -332,18 +388,18 @@ class Request ...@@ -332,18 +388,18 @@ class Request
*/ */
public static function sendMessage(array $data) public static function sendMessage(array $data)
{ {
if (empty($data)) {
throw new TelegramException('Data is empty!');
}
$text = $data['text']; $text = $data['text'];
$string_len_utf8 = mb_strlen($text, 'UTF-8');
if ($string_len_utf8 > 4096) { do {
//Chop off and send the first message
$data['text'] = mb_substr($text, 0, 4096); $data['text'] = mb_substr($text, 0, 4096);
self::send('sendMessage', $data); $response = self::send('sendMessage', $data);
$data['text'] = mb_substr($text, 4096, $string_len_utf8);
return self::sendMessage($data); //Prepare the next message
} $text = mb_substr($text, 4096);
return self::send('sendMessage', $data); } while (mb_strlen($text, 'UTF-8') > 0);
return $response;
} }
/** /**
...@@ -356,10 +412,6 @@ class Request ...@@ -356,10 +412,6 @@ class Request
*/ */
public static function forwardMessage(array $data) public static function forwardMessage(array $data)
{ {
if (empty($data)) {
throw new TelegramException('Data is empty!');
}
return self::send('forwardMessage', $data); return self::send('forwardMessage', $data);
} }
...@@ -374,13 +426,7 @@ class Request ...@@ -374,13 +426,7 @@ class Request
*/ */
public static function sendPhoto(array $data, $file = null) public static function sendPhoto(array $data, $file = null)
{ {
if (empty($data)) { self::assignEncodedFile($data, 'photo', $file);
throw new TelegramException('Data is empty!');
}
if (!is_null($file)) {
$data['photo'] = self::encodeFile($file);
}
return self::send('sendPhoto', $data); return self::send('sendPhoto', $data);
} }
...@@ -396,13 +442,7 @@ class Request ...@@ -396,13 +442,7 @@ class Request
*/ */
public static function sendAudio(array $data, $file = null) public static function sendAudio(array $data, $file = null)
{ {
if (empty($data)) { self::assignEncodedFile($data, 'audio', $file);
throw new TelegramException('Data is empty!');
}
if (!is_null($file)) {
$data['audio'] = self::encodeFile($file);
}
return self::send('sendAudio', $data); return self::send('sendAudio', $data);
} }
...@@ -418,13 +458,7 @@ class Request ...@@ -418,13 +458,7 @@ class Request
*/ */
public static function sendDocument(array $data, $file = null) public static function sendDocument(array $data, $file = null)
{ {
if (empty($data)) { self::assignEncodedFile($data, 'document', $file);
throw new TelegramException('Data is empty!');
}
if (!is_null($file)) {
$data['document'] = self::encodeFile($file);
}
return self::send('sendDocument', $data); return self::send('sendDocument', $data);
} }
...@@ -440,13 +474,7 @@ class Request ...@@ -440,13 +474,7 @@ class Request
*/ */
public static function sendSticker(array $data, $file = null) public static function sendSticker(array $data, $file = null)
{ {
if (empty($data)) { self::assignEncodedFile($data, 'sticker', $file);
throw new TelegramException('Data is empty!');
}
if (!is_null($file)) {
$data['sticker'] = self::encodeFile($file);
}
return self::send('sendSticker', $data); return self::send('sendSticker', $data);
} }
...@@ -462,13 +490,7 @@ class Request ...@@ -462,13 +490,7 @@ class Request
*/ */
public static function sendVideo(array $data, $file = null) public static function sendVideo(array $data, $file = null)
{ {
if (empty($data)) { self::assignEncodedFile($data, 'video', $file);
throw new TelegramException('Data is empty!');
}
if (!is_null($file)) {
$data['video'] = self::encodeFile($file);
}
return self::send('sendVideo', $data); return self::send('sendVideo', $data);
} }
...@@ -484,13 +506,7 @@ class Request ...@@ -484,13 +506,7 @@ class Request
*/ */
public static function sendVoice(array $data, $file = null) public static function sendVoice(array $data, $file = null)
{ {
if (empty($data)) { self::assignEncodedFile($data, 'voice', $file);
throw new TelegramException('Data is empty!');
}
if (!is_null($file)) {
$data['voice'] = self::encodeFile($file);
}
return self::send('sendVoice', $data); return self::send('sendVoice', $data);
} }
...@@ -505,10 +521,6 @@ class Request ...@@ -505,10 +521,6 @@ class Request
*/ */
public static function sendLocation(array $data) public static function sendLocation(array $data)
{ {
if (empty($data)) {
throw new TelegramException('Data is empty!');
}
return self::send('sendLocation', $data); return self::send('sendLocation', $data);
} }
...@@ -522,10 +534,6 @@ class Request ...@@ -522,10 +534,6 @@ class Request
*/ */
public static function sendVenue(array $data) public static function sendVenue(array $data)
{ {
if (empty($data)) {
throw new TelegramException('Data is empty!');
}
return self::send('sendVenue', $data); return self::send('sendVenue', $data);
} }
...@@ -539,10 +547,6 @@ class Request ...@@ -539,10 +547,6 @@ class Request
*/ */
public static function sendContact(array $data) public static function sendContact(array $data)
{ {
if (empty($data)) {
throw new TelegramException('Data is empty!');
}
return self::send('sendContact', $data); return self::send('sendContact', $data);
} }
...@@ -556,10 +560,6 @@ class Request ...@@ -556,10 +560,6 @@ class Request
*/ */
public static function sendChatAction(array $data) public static function sendChatAction(array $data)
{ {
if (empty($data)) {
throw new TelegramException('Data is empty!');
}
return self::send('sendChatAction', $data); return self::send('sendChatAction', $data);
} }
...@@ -573,10 +573,6 @@ class Request ...@@ -573,10 +573,6 @@ class Request
*/ */
public static function getUserProfilePhotos(array $data) public static function getUserProfilePhotos(array $data)
{ {
if (empty($data)) {
throw new TelegramException('Data is empty!');
}
if (!isset($data['user_id'])) { if (!isset($data['user_id'])) {
throw new TelegramException('User id is empty!'); throw new TelegramException('User id is empty!');
} }
...@@ -590,6 +586,7 @@ class Request ...@@ -590,6 +586,7 @@ class Request
* @param array $data * @param array $data
* *
* @return mixed * @return mixed
* @throws \Longman\TelegramBot\Exception\TelegramException
*/ */
public static function getUpdates(array $data) public static function getUpdates(array $data)
{ {
...@@ -603,14 +600,13 @@ class Request ...@@ -603,14 +600,13 @@ class Request
* @param string $file * @param string $file
* *
* @return mixed * @return mixed
* @throws \Longman\TelegramBot\Exception\TelegramException
*/ */
public static function setWebhook($url = '', $file = null) public static function setWebhook($url = '', $file = null)
{ {
$data = ['url' => $url]; $data = ['url' => $url];
if (!is_null($file)) { self::assignEncodedFile($data, 'certificate', $file);
$data['certificate'] = self::encodeFile($file);
}
return self::send('setWebhook', $data); return self::send('setWebhook', $data);
} }
...@@ -625,10 +621,6 @@ class Request ...@@ -625,10 +621,6 @@ class Request
*/ */
public static function getFile(array $data) public static function getFile(array $data)
{ {
if (empty($data)) {
throw new TelegramException('Data is empty!');
}
return self::send('getFile', $data); return self::send('getFile', $data);
} }
...@@ -642,10 +634,6 @@ class Request ...@@ -642,10 +634,6 @@ class Request
*/ */
public static function kickChatMember(array $data) public static function kickChatMember(array $data)
{ {
if (empty($data)) {
throw new TelegramException('Data is empty!');
}
return self::send('kickChatMember', $data); return self::send('kickChatMember', $data);
} }
...@@ -659,10 +647,6 @@ class Request ...@@ -659,10 +647,6 @@ class Request
*/ */
public static function leaveChat(array $data) public static function leaveChat(array $data)
{ {
if (empty($data)) {
throw new TelegramException('Data is empty!');
}
return self::send('leaveChat', $data); return self::send('leaveChat', $data);
} }
...@@ -676,10 +660,6 @@ class Request ...@@ -676,10 +660,6 @@ class Request
*/ */
public static function unbanChatMember(array $data) public static function unbanChatMember(array $data)
{ {
if (empty($data)) {
throw new TelegramException('Data is empty!');
}
return self::send('unbanChatMember', $data); return self::send('unbanChatMember', $data);
} }
...@@ -695,10 +675,6 @@ class Request ...@@ -695,10 +675,6 @@ class Request
*/ */
public static function getChat(array $data) public static function getChat(array $data)
{ {
if (empty($data)) {
throw new TelegramException('Data is empty!');
}
return self::send('getChat', $data); return self::send('getChat', $data);
} }
...@@ -714,10 +690,6 @@ class Request ...@@ -714,10 +690,6 @@ class Request
*/ */
public static function getChatAdministrators(array $data) public static function getChatAdministrators(array $data)
{ {
if (empty($data)) {
throw new TelegramException('Data is empty!');
}
return self::send('getChatAdministrators', $data); return self::send('getChatAdministrators', $data);
} }
...@@ -733,10 +705,6 @@ class Request ...@@ -733,10 +705,6 @@ class Request
*/ */
public static function getChatMembersCount(array $data) public static function getChatMembersCount(array $data)
{ {
if (empty($data)) {
throw new TelegramException('Data is empty!');
}
return self::send('getChatMembersCount', $data); return self::send('getChatMembersCount', $data);
} }
...@@ -752,10 +720,6 @@ class Request ...@@ -752,10 +720,6 @@ class Request
*/ */
public static function getChatMember(array $data) public static function getChatMember(array $data)
{ {
if (empty($data)) {
throw new TelegramException('Data is empty!');
}
return self::send('getChatMember', $data); return self::send('getChatMember', $data);
} }
...@@ -769,10 +733,6 @@ class Request ...@@ -769,10 +733,6 @@ class Request
*/ */
public static function answerCallbackQuery(array $data) public static function answerCallbackQuery(array $data)
{ {
if (empty($data)) {
throw new TelegramException('Data is empty!');
}
return self::send('answerCallbackQuery', $data); return self::send('answerCallbackQuery', $data);
} }
...@@ -786,10 +746,6 @@ class Request ...@@ -786,10 +746,6 @@ class Request
*/ */
public static function answerInlineQuery(array $data) public static function answerInlineQuery(array $data)
{ {
if (empty($data)) {
throw new TelegramException('Data is empty!');
}
return self::send('answerInlineQuery', $data); return self::send('answerInlineQuery', $data);
} }
...@@ -803,10 +759,6 @@ class Request ...@@ -803,10 +759,6 @@ class Request
*/ */
public static function editMessageText(array $data) public static function editMessageText(array $data)
{ {
if (empty($data)) {
throw new TelegramException('Data is empty!');
}
return self::send('editMessageText', $data); return self::send('editMessageText', $data);
} }
...@@ -820,10 +772,6 @@ class Request ...@@ -820,10 +772,6 @@ class Request
*/ */
public static function editMessageCaption(array $data) public static function editMessageCaption(array $data)
{ {
if (empty($data)) {
throw new TelegramException('Data is empty!');
}
return self::send('editMessageCaption', $data); return self::send('editMessageCaption', $data);
} }
...@@ -837,10 +785,6 @@ class Request ...@@ -837,10 +785,6 @@ class Request
*/ */
public static function editMessageReplyMarkup(array $data) public static function editMessageReplyMarkup(array $data)
{ {
if (empty($data)) {
throw new TelegramException('Data is empty!');
}
return self::send('editMessageReplyMarkup', $data); return self::send('editMessageReplyMarkup', $data);
} }
...@@ -850,7 +794,8 @@ class Request ...@@ -850,7 +794,8 @@ class Request
* No request to telegram are sent, this function is used in commands that * No request to telegram are sent, this function is used in commands that
* don't need to fire a message after execution * don't need to fire a message after execution
* *
* @return Entities\ServerResponse * @return \Longman\TelegramBot\Entities\ServerResponse
* @throws \Longman\TelegramBot\Exception\TelegramException
*/ */
public static function emptyResponse() public static function emptyResponse()
{ {
...@@ -888,10 +833,12 @@ class Request ...@@ -888,10 +833,12 @@ class Request
$chats = DB::selectChats($send_groups, $send_super_groups, $send_users, $date_from, $date_to); $chats = DB::selectChats($send_groups, $send_super_groups, $send_users, $date_from, $date_to);
$results = []; $results = [];
if (is_array($chats)) {
foreach ($chats as $row) { foreach ($chats as $row) {
$data['chat_id'] = $row['chat_id']; $data['chat_id'] = $row['chat_id'];
$results[] = call_user_func_array($callback_path . '::' . $callback_function, [$data]); $results[] = call_user_func_array($callback_path . '::' . $callback_function, [$data]);
} }
}
return $results; return $results;
} }
......
...@@ -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, 'offset' => $offset,
'limit' => $limit, 'limit' => $limit,
'timeout' => $timeout, '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) {
$object = call_user_func([$this->update, $update_method]);
if ($object !== null && $from = $object->getFrom()) {
$user_id = $from->getId(); $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