Commit a80ad7ff authored by MBoretto's avatar MBoretto

Merge remote-tracking branch 'upstream/develop' into monolog

parents bf48e732 308d451f
...@@ -50,6 +50,9 @@ try { ...@@ -50,6 +50,9 @@ try {
//$telegram->setDownloadPath('../Download'); //$telegram->setDownloadPath('../Download');
//$telegram->setUploadPath('../Upload'); //$telegram->setUploadPath('../Upload');
//// Botan.io integration
//$telegram->enableBotan('your_token');
// Handle telegram getUpdate request // Handle telegram getUpdate request
$ServerResponse = $telegram->handleGetUpdates(); $ServerResponse = $telegram->handleGetUpdates();
......
...@@ -48,6 +48,9 @@ try { ...@@ -48,6 +48,9 @@ try {
//$telegram->setDownloadPath('../Download'); //$telegram->setDownloadPath('../Download');
//$telegram->setUploadPath('../Upload'); //$telegram->setUploadPath('../Upload');
//// Botan.io integration
//$telegram->enableBotan('your_token');
// Handle telegram webhook request // Handle telegram webhook request
$telegram->handle(); $telegram->handle();
} catch (Longman\TelegramBot\Exception\TelegramException $e) { } catch (Longman\TelegramBot\Exception\TelegramException $e) {
......
<?php
/**
* This file is part of the TelegramBot package.
*
* (c) Avtandil Kikabidze aka LONGMAN <akalongman@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Longman\TelegramBot;
use Longman\TelegramBot\Exception\TelegramException;
/**
* Class Botan
*
* Integration with http://botan.io statistics service for Telegram bots
*/
class Botan
{
/**
* @var string Tracker request url
*/
protected static $track_url = 'https://api.botan.io/track?token=#TOKEN&uid=#UID&name=#NAME';
/**
* @var string Url Shortener request url
*/
protected static $shortener_url = 'https://api.botan.io/s/?token=#TOKEN&user_ids=#UID&url=#URL';
/**
* @var string Yandex AppMetrica application key
*/
protected static $token = '';
/**
* Initilize botan
*/
public static function initializeBotan($token)
{
if (empty($token) || !is_string($token)) {
throw new TelegramException('Botan token should be a string!');
}
self::$token = $token;
BotanDB::initializeBotanDb();
}
/**
* Track function
*
* @todo Advanced integration: https://github.com/botanio/sdk#advanced-integration
*
* @param string $input
* @param string $command
* @return bool|string
*/
public static function track($input, $command = '')
{
if (empty(self::$token)) {
return false;
}
if (empty($input)) {
throw new TelegramException('Input is empty!');
}
$obj = json_decode($input, true);
if (isset($obj['message'])) {
$data = $obj['message'];
if ((isset($obj['message']['entities']) && $obj['message']['entities'][0]['type'] == 'bot_command' && $obj['message']['entities'][0]['offset'] == 0) || substr($obj['message']['text'], 0, 1) == '/') {
if (strtolower($command) == 'generic') {
$command = 'Generic';
} elseif (strtolower($command) == 'genericmessage') {
$command = 'Generic Message';
} else {
$command = '/' . strtolower($command);
}
$event_name = 'Command ('.$command.')';
} else {
$event_name = 'Message';
}
} elseif (isset($obj['inline_query'])) {
$data = $obj['inline_query'];
$event_name = 'Inline Query';
} elseif (isset($obj['chosen_inline_result'])) {
$data = $obj['chosen_inline_result'];
$event_name = 'Chosen Inline Result';
} elseif (isset($obj['callback_query'])) {
$data = $obj['callback_query'];
$event_name = 'Callback Query';
}
if (empty($event_name)) {
return false;
}
$uid = $data['from']['id'];
$request = str_replace(
['#TOKEN', '#UID', '#NAME'],
[self::$token, $uid, urlencode($event_name)],
self::$track_url
);
$options = [
'http' => [
'header' => 'Content-Type: application/json',
'method' => 'POST',
'content' => json_encode($data),
'ignore_errors' => true
]
];
$context = stream_context_create($options);
$response = @file_get_contents($request, false, $context);
$responseData = json_decode($response, true);
if ($responseData['status'] != 'accepted') {
error_log('Botan.io API replied with error: ' . $response);
}
return $responseData;
}
/**
* Url Shortener function
*
* @param $url
* @param $user_id
* @return string
*/
public static function shortenUrl($url, $user_id)
{
if (empty(self::$token)) {
return $url;
}
if (empty($user_id)) {
throw new TelegramException('User id is empty!');
}
$cached = BotanDB::selectShortUrl($user_id, $url);
if (!empty($cached[0]['short_url'])) {
return $cached[0]['short_url'];
}
$request = str_replace(
['#TOKEN', '#UID', '#URL'],
[self::$token, $user_id, urlencode($url)],
self::$shortener_url
);
$options = [
'http' => [
'ignore_errors' => true,
'timeout' => 3
]
];
$context = stream_context_create($options);
$response = @file_get_contents($request, false, $context);
if (!filter_var($response, FILTER_VALIDATE_URL) === false) {
BotanDB::insertShortUrl($user_id, $url, $response);
} else {
error_log('Botan.io API replied with error: ' . $response);
return $url;
}
return $response;
}
}
<?php
/**
* This file is part of the TelegramBot package.
*
* (c) Avtandil Kikabidze aka LONGMAN <akalongman@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Longman\TelegramBot;
use Longman\TelegramBot\DB;
use Longman\TelegramBot\Exception\TelegramException;
/**
* Class BotanDB
*/
class BotanDB extends DB
{
/**
* Initilize botan shortener table
*/
public static function initializeBotanDb()
{
if (!defined('TB_BOTAN_SHORTENER')) {
define('TB_BOTAN_SHORTENER', self::$table_prefix . 'botan_shortener');
}
}
/**
* Select cached shortened URL from the database
*
* @param $user_id
* @param $url
* @return bool|string
* @throws TelegramException
*/
public static function selectShortUrl($user_id, $url)
{
if (!self::isDbConnected()) {
return false;
}
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);
} catch (\Exception $e) {
throw new TelegramException($e->getMessage());
}
return $results;
}
/**
* Insert shortened URL into the database
*
* @param $user_id
* @param $url
* @param $short_url
* @return bool
* @throws TelegramException
*/
public static function insertShortUrl($user_id, $url, $short_url)
{
if (!self::isDbConnected()) {
return false;
}
try {
$sth = self::$pdo->prepare('INSERT INTO `' . TB_BOTAN_SHORTENER . '`
(
`user_id`, `url`, `short_url`, `created_at`
)
VALUES (
:user_id, :url, :short_url, :date
)
');
$created_at = self::getTimestamp();
$sth->bindParam(':user_id', $user_id);
$sth->bindParam(':url', $url);
$sth->bindParam(':short_url', $short_url);
$sth->bindParam(':date', $created_at);
$status = $sth->execute();
} catch (\Exception $e) {
throw new TelegramException($e->getMessage());
}
return $status;
}
}
...@@ -12,6 +12,7 @@ namespace Longman\TelegramBot\Commands\SystemCommands; ...@@ -12,6 +12,7 @@ namespace Longman\TelegramBot\Commands\SystemCommands;
use Longman\TelegramBot\Commands\SystemCommand; use Longman\TelegramBot\Commands\SystemCommand;
use Longman\TelegramBot\Entities\InlineQueryResultArticle; use Longman\TelegramBot\Entities\InlineQueryResultArticle;
use Longman\TelegramBot\Entities\InputTextMessageContent;
use Longman\TelegramBot\Request; use Longman\TelegramBot\Request;
/** /**
...@@ -39,9 +40,9 @@ class InlinequeryCommand extends SystemCommand ...@@ -39,9 +40,9 @@ class InlinequeryCommand extends SystemCommand
$data = ['inline_query_id' => $inline_query->getId()]; $data = ['inline_query_id' => $inline_query->getId()];
$articles = [ $articles = [
['id' => '001', 'title' => 'https://core.telegram.org/bots/api#answerinlinequery', 'message_text' => 'you enter: ' . $query , 'input_message_content' => [ 'message_text' => $query ] ], ['id' => '001', 'title' => 'https://core.telegram.org/bots/api#answerinlinequery', 'message_text' => 'you enter: ' . $query , 'input_message_content' => new InputTextMessageContent([ 'message_text' => $query ]) ],
['id' => '002', 'title' => 'https://core.telegram.org/bots/api#answerinlinequery', 'message_text' => 'you enter: ' . $query , 'input_message_content' => [ 'message_text' => $query ] ], ['id' => '002', 'title' => 'https://core.telegram.org/bots/api#answerinlinequery', 'message_text' => 'you enter: ' . $query , 'input_message_content' => new InputTextMessageContent([ 'message_text' => $query ]) ],
['id' => '003', 'title' => 'https://core.telegram.org/bots/api#answerinlinequery', 'message_text' => 'you enter: ' . $query , 'input_message_content' => [ 'message_text' => $query ] ], ['id' => '003', 'title' => 'https://core.telegram.org/bots/api#answerinlinequery', 'message_text' => 'you enter: ' . $query , 'input_message_content' => new InputTextMessageContent([ 'message_text' => $query ]) ],
]; ];
$array_article = []; $array_article = [];
......
...@@ -75,6 +75,9 @@ class Entity ...@@ -75,6 +75,9 @@ class Entity
} elseif ($array_of_array_obj) { } elseif ($array_of_array_obj) {
foreach ($object->$name as $elm) { foreach ($object->$name as $elm) {
$temp = null; $temp = null;
if (!is_array($elm) && !is_object($elm)) {
continue;
}
foreach ($elm as $obj) { foreach ($elm as $obj) {
$temp[] = $this->reflect($obj); $temp[] = $this->reflect($obj);
} }
......
...@@ -16,9 +16,6 @@ class InlineKeyboardMarkup extends Entity ...@@ -16,9 +16,6 @@ class InlineKeyboardMarkup extends Entity
{ {
protected $inline_keyboard; protected $inline_keyboard;
/**
* @todo check for InlineKeyboardButton elements
*/
public function __construct($data = array()) public function __construct($data = array())
{ {
if (isset($data['inline_keyboard'])) { if (isset($data['inline_keyboard'])) {
......
...@@ -20,16 +20,16 @@ class InputContactMessageContent extends InputMessageContent ...@@ -20,16 +20,16 @@ class InputContactMessageContent extends InputMessageContent
public function __construct(array $data) public function __construct(array $data)
{ {
$this->phone_number isset($data['phone_number']) ? $data['phone_number'] : null; $this->phone_number = isset($data['phone_number']) ? $data['phone_number'] : null;
if (empty($this->phone_number)) { if (empty($this->phone_number)) {
throw new TelegramException('phone_number is empty!'); throw new TelegramException('phone_number is empty!');
} }
$this->first_name isset($data['first_name']) ? $data['first_name'] : null; $this->first_name = isset($data['first_name']) ? $data['first_name'] : null;
if (empty($this->first_name)) { if (empty($this->first_name)) {
throw new TelegramException('first_name is empty!'); throw new TelegramException('first_name is empty!');
} }
$this->last_name isset($data['last_name']) ? $data['last_name'] : null; $this->last_name = isset($data['last_name']) ? $data['last_name'] : null;
} }
} }
...@@ -19,12 +19,12 @@ class InputLocationMessageContent extends InputMessageContent ...@@ -19,12 +19,12 @@ class InputLocationMessageContent extends InputMessageContent
public function __construct(array $data) public function __construct(array $data)
{ {
$this->latitude isset($data['latitude']) ? $data['latitude'] : null; $this->latitude = isset($data['latitude']) ? $data['latitude'] : null;
if (empty($this->latitude)) { if (empty($this->latitude)) {
throw new TelegramException('latitude is empty!'); throw new TelegramException('latitude is empty!');
} }
$this->longitude isset($data['longitude']) ? $data['longitude'] : null; $this->longitude = isset($data['longitude']) ? $data['longitude'] : null;
if (empty($this->longitude)) { if (empty($this->longitude)) {
throw new TelegramException('longitude is empty!'); throw new TelegramException('longitude is empty!');
} }
......
...@@ -20,12 +20,12 @@ class InputTextMessageContent extends InputMessageContent ...@@ -20,12 +20,12 @@ class InputTextMessageContent extends InputMessageContent
public function __construct(array $data) public function __construct(array $data)
{ {
$this->message_text isset($data['message_text']) ? $data['message_text'] : null; $this->message_text = isset($data['message_text']) ? $data['message_text'] : null;
if (empty($this->message_text)) { if (empty($this->message_text)) {
throw new TelegramException('message_text is empty!'); throw new TelegramException('message_text is empty!');
} }
$this->parse_mode isset($data['parse_mode']) ? $data['parse_mode'] : null; $this->parse_mode = isset($data['parse_mode']) ? $data['parse_mode'] : null;
$this->disable_web_page_preview isset($data['disable_web_page_preview']) ? $data['disable_web_page_preview'] : null; $this->disable_web_page_preview = isset($data['disable_web_page_preview']) ? $data['disable_web_page_preview'] : null;
} }
} }
...@@ -22,26 +22,26 @@ class InputVenueMessageContent extends InputMessageContent ...@@ -22,26 +22,26 @@ class InputVenueMessageContent extends InputMessageContent
public function __construct(array $data) public function __construct(array $data)
{ {
$this->latitude isset($data['latitude']) ? $data['latitude'] : null; $this->latitude = isset($data['latitude']) ? $data['latitude'] : null;
if (empty($this->latitude)) { if (empty($this->latitude)) {
throw new TelegramException('latitude is empty!'); throw new TelegramException('latitude is empty!');
} }
$this->longitude isset($data['longitude']) ? $data['longitude'] : null; $this->longitude = isset($data['longitude']) ? $data['longitude'] : null;
if (empty($this->longitude)) { if (empty($this->longitude)) {
throw new TelegramException('longitude is empty!'); throw new TelegramException('longitude is empty!');
} }
$this->title isset($data['title']) ? $data['title'] : null; $this->title = isset($data['title']) ? $data['title'] : null;
if (empty($this->title)) { if (empty($this->title)) {
throw new TelegramException('title is empty!'); throw new TelegramException('title is empty!');
} }
$this->address isset($data['address']) ? $data['address'] : null; $this->address = isset($data['address']) ? $data['address'] : null;
if (empty($this->address)) { if (empty($this->address)) {
throw new TelegramException('address is empty!'); throw new TelegramException('address is empty!');
} }
$this->foursquare_id isset($data['foursquare_id']) ? $data['foursquare_id'] : null; $this->foursquare_id = isset($data['foursquare_id']) ? $data['foursquare_id'] : null;
} }
} }
...@@ -21,9 +21,6 @@ class ReplyKeyboardMarkup extends Entity ...@@ -21,9 +21,6 @@ class ReplyKeyboardMarkup extends Entity
protected $one_time_keyboard; protected $one_time_keyboard;
protected $selective; protected $selective;
/**
* @todo check for KeyboardButton elements
*/
public function __construct($data = array()) public function __construct($data = array())
{ {
if (isset($data['keyboard'])) { if (isset($data['keyboard'])) {
......
...@@ -199,6 +199,8 @@ class Request ...@@ -199,6 +199,8 @@ class Request
self::setInputRaw($result); self::setInputRaw($result);
} }
curl_close($ch);
if ($result === false) { if ($result === false) {
throw new TelegramException(curl_error($ch), curl_errno($ch)); throw new TelegramException(curl_error($ch), curl_errno($ch));
} }
...@@ -206,7 +208,6 @@ class Request ...@@ -206,7 +208,6 @@ class Request
throw new TelegramException('Empty server response'); throw new TelegramException('Empty server response');
} }
curl_close($ch);
return $result; return $result;
} }
......
...@@ -137,6 +137,13 @@ class Telegram ...@@ -137,6 +137,13 @@ class Telegram
*/ */
protected $last_command_response; protected $last_command_response;
/**
* Botan.io integration
*
* @var boolean
*/
protected $botan_enabled = false;
/** /**
* Constructor * Constructor
* *
...@@ -490,6 +497,11 @@ class Telegram ...@@ -490,6 +497,11 @@ class Telegram
//execute() method is executed after preExecute() //execute() method is executed after preExecute()
//This is to prevent executing a DB query without a valid connection //This is to prevent executing a DB query without a valid connection
$this->last_command_response = $command_obj->preExecute(); $this->last_command_response = $command_obj->preExecute();
//Botan.io integration
if ($this->botan_enabled) {
Botan::track($this->input, $command);
}
} }
return $this->last_command_response; return $this->last_command_response;
...@@ -770,4 +782,18 @@ class Telegram ...@@ -770,4 +782,18 @@ class Telegram
{ {
return mb_strtoupper(mb_substr($str, 0, 1, $encoding), $encoding) . mb_strtolower(mb_substr($str, 1, mb_strlen($str), $encoding), $encoding); return mb_strtoupper(mb_substr($str, 0, 1, $encoding), $encoding) . mb_strtolower(mb_substr($str, 1, mb_strlen($str), $encoding), $encoding);
} }
/**
* Enable Botan.io integration
*
* @param $token
* @param $custom
* @return Telegram
*/
public function enableBotan($token)
{
Botan::initializeBotan($token);
$this->botan_enabled = true;
return $this;
}
} }
...@@ -171,3 +171,14 @@ CREATE TABLE IF NOT EXISTS `conversation` ( ...@@ -171,3 +171,14 @@ CREATE TABLE IF NOT EXISTS `conversation` (
FOREIGN KEY (`chat_id`) FOREIGN KEY (`chat_id`)
REFERENCES `chat` (`id`) REFERENCES `chat` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci; ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci;
CREATE TABLE IF NOT EXISTS `botan_shortener` (
`id` bigint UNSIGNED AUTO_INCREMENT COMMENT 'Unique identifier for this entry.',
`user_id` bigint NULL DEFAULT NULL COMMENT 'Unique user identifier',
`url` text NOT NULL DEFAULT '' COMMENT 'Original URL',
`short_url` CHAR(255) NOT NULL DEFAULT '' COMMENT 'Shortened URL',
`created_at` timestamp NULL DEFAULT NULL COMMENT 'Entry date creation',
PRIMARY KEY (`id`),
FOREIGN KEY (`user_id`) REFERENCES `user` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci;
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