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