Commit 4f822d87 authored by Jack'lul's avatar Jack'lul

Apply improvements suggested by @noplanman in #365

parent 8a1c8953
...@@ -64,7 +64,7 @@ try { ...@@ -64,7 +64,7 @@ try {
// Botan.io integration // Botan.io integration
// Second argument is optional maximum timeout // Second argument is optional maximum timeout
//$telegram->enableBotan('your_token'); //$telegram->enableBotan('your_token');
//$telegram->enableBotan('your_token', 3); //$telegram->enableBotan('your_token', ['timeout' => 3]);
// Handle telegram getUpdates request // Handle telegram getUpdates request
$serverResponse = $telegram->handleGetUpdates(); $serverResponse = $telegram->handleGetUpdates();
......
...@@ -63,7 +63,7 @@ try { ...@@ -63,7 +63,7 @@ try {
// Botan.io integration // Botan.io integration
// Second argument is optional maximum timeout // Second argument is optional maximum timeout
//$telegram->enableBotan('your_token'); //$telegram->enableBotan('your_token');
//$telegram->enableBotan('your_token', 3); //$telegram->enableBotan('your_token', ['timeout' => 3]);
// Handle telegram webhook request // Handle telegram webhook request
$telegram->handle(); $telegram->handle();
......
...@@ -48,7 +48,7 @@ class Botan ...@@ -48,7 +48,7 @@ class Botan
* *
* Set as public to let the developers either: * Set as public to let the developers either:
* - block tracking from inside commands by setting the value to non-existent command * - block tracking from inside commands by setting the value to non-existent command
* - override which command is tracked when commands call other commands with executedCommand() * - override which command is tracked when commands call other commands with executeCommand()
* *
* @var string * @var string
*/ */
...@@ -58,22 +58,28 @@ class Botan ...@@ -58,22 +58,28 @@ class Botan
* Initialize Botan * Initialize Botan
* *
* @param string $token * @param string $token
* @param integer $timeout * @param array $options
* *
* @throws \Longman\TelegramBot\Exception\TelegramException * @throws \Longman\TelegramBot\Exception\TelegramException
*/ */
public static function initializeBotan($token, $timeout = 3) public static function initializeBotan($token, array $options = [])
{ {
if (empty($token)) { if (empty($token)) {
throw new TelegramException('Botan token is empty!'); throw new TelegramException('Botan token is empty!');
} }
if (!is_numeric($timeout)) { $options_default = [
'timeout' => 3
];
$options = array_merge($options_default, $options);
if (!is_numeric($options['timeout'])) {
throw new TelegramException('Timeout must be a number!'); throw new TelegramException('Timeout must be a number!');
} }
self::$token = $token; self::$token = $token;
self::$client = new Client(['base_uri' => self::$api_base_uri, 'timeout' => $timeout]); self::$client = new Client(['base_uri' => self::$api_base_uri, 'timeout' => $options['timeout']]);
BotanDB::initializeBotanDb(); BotanDB::initializeBotanDb();
} }
...@@ -81,7 +87,7 @@ class Botan ...@@ -81,7 +87,7 @@ class Botan
/** /**
* Lock function to make sure only the first command is reported (the one user requested) * Lock function to make sure only the first command is reported (the one user requested)
* *
* This is in case commands are calling other commands with executedCommand() * This is in case commands are calling other commands with executeCommand()
* *
* @param string $command * @param string $command
*/ */
...@@ -103,7 +109,9 @@ class Botan ...@@ -103,7 +109,9 @@ class Botan
*/ */
public static function track(Update $update, $command = '') public static function track(Update $update, $command = '')
{ {
if (empty(self::$token) || strtolower($command) !== self::$command) { $command = strtolower($command);
if (empty(self::$token) || $command !== self::$command) {
return false; return false;
} }
...@@ -111,69 +119,61 @@ class Botan ...@@ -111,69 +119,61 @@ class Botan
throw new TelegramException('Update object is empty!'); throw new TelegramException('Update object is empty!');
} }
// Release the lock in case someone runs getUpdates in foreach loop // Release the lock in case this is getUpdates instance in foreach loop
self::$command = ''; self::$command = '';
// For now, this is the only way
$update_data = (array) $update;
$data = []; $data = [];
if ($update->getMessage()) { $update_data = (array) $update; // For now, this is the only way
$data = $update_data['message']; $update_type = $update->getUpdateType();
$event_name = 'Message';
$update_object_names = [
if (!empty($data['entities']) && is_array($data['entities'])) { 'message' => 'Message',
foreach ($data['entities'] as $entity) { 'edited_message' => 'Edited Message',
if ($entity['type'] === 'bot_command' && $entity['offset'] === 0) { 'channel_post' => 'Channel Post',
if (strtolower($command) === 'generic') { 'edited_channel_post' => 'Edited Channel Post',
$command = 'Generic'; 'inline_query' => 'Inline Query',
} elseif (strtolower($command) === 'genericmessage') { 'chosen_inline_result' => 'Chosen Inline Result',
$command = 'Generic Message'; 'callback_query' => 'Callback Query'
} else { ];
$command = '/' . strtolower($command);
if (in_array($update_type, ['message', 'edited_message', 'channel_post', 'edited_channel_post', 'inline_query', 'chosen_inline_result', 'callback_query'], true)) {
$data = $update_data[$update_type];
$event_name = $update_object_names[$update_type];
if ($update_type === 'message') {
if ($update->getMessage()->getEntities()) {
foreach ($update->getMessage()->getEntities() as $entity) {
if ($entity->getType() === 'bot_command' && $entity->getOffset() === 0) {
if ($command === 'generic') {
$command = 'Generic';
} elseif ($command === 'genericmessage') { // This should not happen as it equals normal message but leaving it as a fail-safe
$command = 'Generic Message';
} else {
$command = '/' . $command;
}
$event_name = 'Command (' . $command . ')';
break;
} }
$event_name = 'Command (' . $command . ')';
break;
} }
} }
} }
} elseif ($update->getEditedMessage()) {
$data = $update_data['edited_message'];
$event_name = 'Edited Message';
} elseif ($update->getChannelPost()) {
$data = $update_data['channel_post'];
$event_name = 'Channel Post';
} elseif ($update->getEditedChannelPost()) {
$data = $update_data['edited_channel_post'];
$event_name = 'Edited Channel Post';
} elseif ($update->getInlineQuery()) {
$data = $update_data['inline_query'];
$event_name = 'Inline Query';
} elseif ($update->getChosenInlineResult()) {
$data = $update_data['chosen_inline_result'];
$event_name = 'Chosen Inline Result';
} elseif ($update->getCallbackQuery()) {
$data = $update_data['callback_query'];
$event_name = 'Callback Query';
} }
if (empty($event_name)) { if (empty($event_name)) {
TelegramLog::error("Botan.io stats report failed, no suitable update object found!");
return false; return false;
} }
// In case there is no from field (channel posts) assign chat id // In case there is no from field assign id = 0
if (isset($data['from']['id'])) { if (isset($data['from']['id'])) {
$uid = $data['from']['id']; $uid = $data['from']['id'];
} elseif (isset($data['chat']['id'])) {
$uid = $data['chat']['id'];
} else { } else {
$uid = 0; // if that fails too assign id = 0 $uid = 0;
} }
try { try {
$response = self::$client->request( $response = self::$client->post(
'POST',
str_replace( str_replace(
['#TOKEN', '#UID', '#NAME'], ['#TOKEN', '#UID', '#NAME'],
[self::$token, $uid, urlencode($event_name)], [self::$token, $uid, urlencode($event_name)],
...@@ -195,9 +195,9 @@ class Botan ...@@ -195,9 +195,9 @@ class Botan
if ($responseData['status'] !== 'accepted') { if ($responseData['status'] !== 'accepted') {
if (!empty($response)) { if (!empty($response)) {
TelegramLog::debug("Botan.io track post failed, API reply:\n$response\n\n"); TelegramLog::debug("Botan.io stats report failed, API reply: $response");
} else { } else {
TelegramLog::debug("Botan.io track post failed, API returned empty response!\n\n"); TelegramLog::debug("Botan.io stats report failed, API returned empty response!");
} }
return false; return false;
...@@ -210,7 +210,7 @@ class Botan ...@@ -210,7 +210,7 @@ class Botan
/** /**
* Url Shortener function * Url Shortener function
* *
* @param string $url * @param string $url
* @param integer $user_id * @param integer $user_id
* *
* @return string * @return string
...@@ -226,15 +226,12 @@ class Botan ...@@ -226,15 +226,12 @@ class Botan
throw new TelegramException('User id is empty!'); throw new TelegramException('User id is empty!');
} }
$cached = BotanDB::selectShortUrl($user_id, $url); if ($cached = BotanDB::selectShortUrl($user_id, $url)) {
if (!empty($cached)) {
return $cached; return $cached;
} }
try { try {
$response = self::$client->request( $response = self::$client->post(
'POST',
str_replace( str_replace(
['#TOKEN', '#UID', '#URL'], ['#TOKEN', '#UID', '#URL'],
[self::$token, $user_id, urlencode($url)], [self::$token, $user_id, urlencode($url)],
...@@ -246,14 +243,14 @@ class Botan ...@@ -246,14 +243,14 @@ class Botan
} catch (RequestException $e) { } catch (RequestException $e) {
$response = ($e->getResponse()) ? (string) $e->getResponse()->getBody() : ''; $response = ($e->getResponse()) ? (string) $e->getResponse()->getBody() : '';
} finally { } finally {
if (!filter_var($response, FILTER_VALIDATE_URL) === false) { if (filter_var($response, FILTER_VALIDATE_URL) !== false) {
BotanDB::insertShortUrl($user_id, $url, $response); BotanDB::insertShortUrl($user_id, $url, $response);
return $response; return $response;
} else { } else {
if (!empty($response)) { if (!empty($response)) {
TelegramLog::debug("Botan.io URL shortening failed for '$url', API reply:\n$response\n\n"); TelegramLog::debug("Botan.io URL shortening failed for '$url', API reply: $response");
} else { } else {
TelegramLog::debug("Botan.io URL shortening failed for '$url', API returned empty response!\n\n"); TelegramLog::debug("Botan.io URL shortening failed for '$url', API returned empty response!");
} }
return $url; return $url;
......
...@@ -817,14 +817,14 @@ class Telegram ...@@ -817,14 +817,14 @@ class Telegram
* Enable Botan.io integration * Enable Botan.io integration
* *
* @param string $token * @param string $token
* @param integer $timeout * @param array $options
* *
* @return \Longman\TelegramBot\Telegram * @return \Longman\TelegramBot\Telegram
* @throws \Longman\TelegramBot\Exception\TelegramException * @throws \Longman\TelegramBot\Exception\TelegramException
*/ */
public function enableBotan($token, $timeout = 3) public function enableBotan($token, array $options = [])
{ {
Botan::initializeBotan($token, $timeout); Botan::initializeBotan($token, $options);
$this->botan_enabled = true; $this->botan_enabled = true;
return $this; return $this;
......
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