Completely remove Botan.io integration.

parent 9ae0cdea
......@@ -8,6 +8,7 @@ Exclamation symbols (:exclamation:) note something of importance e.g. breaking c
### Changed
### Deprecated
### Removed
- Botan.io integration completely removed.
### Fixed
- `forward_date` is now correctly saved to the DB.
### Security
......
......@@ -39,7 +39,6 @@ A Telegram Bot based on the official [Telegram Bot API][Telegram-Bot-API]
- [Utils](#utils)
- [MySQL storage (Recommended)](#mysql-storage-recommended)
- [Channels Support](#channels-support)
- [Botan.io integration (Optional)](#botanio-integration-optional)
- [Commands](#commands)
- [Predefined Commands](#predefined-commands)
- [Custom Commands](#custom-commands)
......@@ -81,7 +80,6 @@ The Bot can:
- full support for **inline bots**.
- inline keyboard.
- Messages, InlineQuery and ChosenInlineQuery are stored in the Database.
- *Botan.io* integration and database cache system. (**new!**)
- Conversation feature
-----
......@@ -444,29 +442,6 @@ $telegram->enableExternalMySql($external_pdo_connection)
All methods implemented can be used to manage channels.
With [admin commands](#admin-commands) you can manage your channels directly with your bot private chat.
### Botan.io integration (Optional)
You can enable the integration using this line in you `hook.php`:
```php
$telegram->enableBotan('your_token');
```
Replace `your_token` with your Botan.io token, check [this page](https://github.com/botanio/sdk#creating-an-account) to see how to obtain one.
The following actions will be tracked:
- Commands (shown as `Command (/command_name)` in the stats
- Inline Queries, Chosen Inline Results and Callback Queries
- Messages sent to the bot (or replies in groups)
In order to use the URL shortener you must include the class `use Longman\TelegramBot\Botan;` and call it like this:
```php
Botan::shortenUrl('https://github.com/php-telegram-bot/core', $user_id);
```
Shortened URLs are cached in the database (if MySQL storage is enabled).
### Commands
#### Predefined Commands
......
<?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 GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;
use Longman\TelegramBot\Entities\Update;
use Longman\TelegramBot\Exception\TelegramException;
/**
* Class Botan
*
* @deprecated Botan.io service is no longer working
*
* Integration with http://botan.io statistics service for Telegram bots
*/
class Botan
{
/**
* Botan.io API URL
*
* @var string
*/
protected static $api_base_uri = 'https://api.botan.io';
/**
* Yandex AppMetrica application key
*
* @var string
*/
protected static $token = '';
/**
* Guzzle Client object
*
* @var \GuzzleHttp\Client
*/
private static $client;
/**
* The actual command that is going to be reported
*
* Set as public to let the developers either:
* - block tracking from inside commands by setting the value to non-existent command
* - override which command is tracked when commands call other commands with executeCommand()
*
* @var string
*/
public static $command = '';
/**
* Initialize Botan
*
* @param string $token
* @param array $options
*
* @throws \Longman\TelegramBot\Exception\TelegramException
*/
public static function initializeBotan($token, array $options = [])
{
trigger_error('Longman\TelegramBot\Botan::initializeBotan is deprecated and will be removed in future release.', E_USER_DEPRECATED);
if (empty($token)) {
throw new TelegramException('Botan token is empty!');
}
$options_default = [
'timeout' => 3,
];
$options = array_merge($options_default, $options);
if (!is_numeric($options['timeout'])) {
throw new TelegramException('Timeout must be a number!');
}
self::$token = $token;
self::$client = new Client(['base_uri' => self::$api_base_uri, 'timeout' => $options['timeout']]);
BotanDB::initializeBotanDb();
}
/**
* 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 executeCommand()
*
* @param string $command
*/
public static function lock($command = '')
{
if (empty(self::$command)) {
self::$command = strtolower($command);
}
}
/**
* Track function
*
* @param \Longman\TelegramBot\Entities\Update $update
* @param string $command
*
* @return bool|string
* @throws \Longman\TelegramBot\Exception\TelegramException
*/
public static function track(Update $update, $command = '')
{
$command = strtolower($command);
if (empty(self::$token) || $command !== self::$command) {
return false;
}
if ($update === null) {
throw new TelegramException('Update object is empty!');
}
// Release the lock in case this is getUpdates instance in foreach loop
self::$command = '';
$data = [];
$update_data = (array) $update; // For now, this is the only way
$update_type = $update->getUpdateType();
$update_object_names = [
'message' => 'Message',
'edited_message' => 'Edited Message',
'channel_post' => 'Channel Post',
'edited_channel_post' => 'Edited Channel Post',
'inline_query' => 'Inline Query',
'chosen_inline_result' => 'Chosen Inline Result',
'callback_query' => 'Callback Query',
];
if (array_key_exists($update_type, $update_object_names)) {
$data = $update_data[$update_type];
$event_name = $update_object_names[$update_type];
if ($update_type === 'message' && $entities = $update->getMessage()->getEntities()) {
foreach ($entities 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;
}
}
}
}
if (empty($event_name)) {
TelegramLog::error('Botan.io stats report failed, no suitable update object found!');
return false;
}
// In case there is no from field assign id = 0
$uid = isset($data['from']['id']) ? $data['from']['id'] : 0;
try {
$response = self::$client->post(
sprintf(
'/track?token=%1$s&uid=%2$s&name=%3$s',
self::$token,
$uid,
urlencode($event_name)
),
[
'headers' => [
'Content-Type' => 'application/json',
],
'json' => $data,
]
);
$result = (string) $response->getBody();
} catch (RequestException $e) {
$result = $e->getMessage();
}
$responseData = json_decode($result, true);
if (!$responseData || $responseData['status'] !== 'accepted') {
TelegramLog::debug('Botan.io stats report failed: %s', $result ?: 'empty response');
return false;
}
return $responseData;
}
/**
* Url Shortener function
*
* @param string $url
* @param integer $user_id
*
* @return string
* @throws \Longman\TelegramBot\Exception\TelegramException
*/
public static function shortenUrl($url, $user_id)
{
if (empty(self::$token)) {
return $url;
}
if (empty($user_id)) {
throw new TelegramException('User id is empty!');
}
if ($cached = BotanDB::selectShortUrl($url, $user_id)) {
return $cached;
}
try {
$response = self::$client->post(
sprintf(
'/s?token=%1$s&user_ids=%2$s&url=%3$s',
self::$token,
$user_id,
urlencode($url)
)
);
$result = (string) $response->getBody();
} catch (RequestException $e) {
$result = $e->getMessage();
}
if (filter_var($result, FILTER_VALIDATE_URL) === false) {
TelegramLog::debug('Botan.io URL shortening failed for "%s": %s', $url, $result ?: 'empty response');
return $url;
}
BotanDB::insertShortUrl($url, $user_id, $result);
return $result;
}
}
<?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 Exception;
use Longman\TelegramBot\Exception\TelegramException;
/**
* Class BotanDB
*
* @deprecated Botan.io service is no longer working
*/
class BotanDB extends DB
{
/**
* Initialize 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 string $url
* @param string $user_id
*
* @return array|bool
* @throws TelegramException
*/
public static function selectShortUrl($url, $user_id)
{
if (!self::isDbConnected()) {
return false;
}
try {
$sth = self::$pdo->prepare('
SELECT `short_url`
FROM `' . TB_BOTAN_SHORTENER . '`
WHERE `user_id` = :user_id
AND `url` = :url
ORDER BY `created_at` DESC
LIMIT 1
');
$sth->bindValue(':user_id', $user_id);
$sth->bindValue(':url', $url);
$sth->execute();
return $sth->fetchColumn();
} catch (Exception $e) {
throw new TelegramException($e->getMessage());
}
}
/**
* Insert shortened URL into the database
*
* @param string $url
* @param string $user_id
* @param string $short_url
*
* @return bool
* @throws TelegramException
*/
public static function insertShortUrl($url, $user_id, $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, :created_at)
');
$sth->bindValue(':user_id', $user_id);
$sth->bindValue(':url', $url);
$sth->bindValue(':short_url', $short_url);
$sth->bindValue(':created_at', self::getTimestamp());
return $sth->execute();
} catch (Exception $e) {
throw new TelegramException($e->getMessage());
}
}
}
......@@ -68,7 +68,6 @@ class CleanupCommand extends AdminCommand
* @var array
*/
protected static $default_tables_to_clean = [
'botan_shortener',
'callback_query',
'chosen_inline_result',
'conversation',
......@@ -85,7 +84,6 @@ class CleanupCommand extends AdminCommand
* @var array
*/
protected static $default_clean_older_than = [
'botan_shortener' => '30 days',
'chat' => '365 days',
'callback_query' => '30 days',
'chosen_inline_result' => '30 days',
......@@ -242,11 +240,6 @@ class CleanupCommand extends AdminCommand
'request_limiter' => ['table' => TB_REQUEST_LIMITER, 'field' => 'created_at'],
];
// Botan table is only available if enabled.
if (defined('TB_BOTAN_SHORTENER')) {
$simple_tables['botan_shortener'] = ['table' => TB_BOTAN_SHORTENER, 'field' => 'created_at'];
}
foreach (array_intersect(array_keys($simple_tables), $tables_to_clean) as $table_to_clean) {
$queries[] = sprintf(
'DELETE FROM `%1$s`
......
......@@ -874,23 +874,6 @@ class Telegram
. mb_strtolower(mb_substr($str, 1, mb_strlen($str), $encoding), $encoding);
}
/**
* Enable Botan.io integration
*
* @deprecated Botan.io service is no longer working
*
* @param string $token
* @param array $options
*
* @return \Longman\TelegramBot\Telegram
*/
public function enableBotan($token, array $options = [])
{
trigger_error('Longman\TelegramBot\Telegram::enableBotan is deprecated and will be removed in future release.', E_USER_DEPRECATED);
return $this;
}
/**
* Enable requests limiter
*
......
......@@ -271,18 +271,6 @@ CREATE TABLE IF NOT EXISTS `conversation` (
FOREIGN KEY (`chat_id`) REFERENCES `chat` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_520_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 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=utf8mb4 COLLATE=utf8mb4_unicode_520_ci;
CREATE TABLE IF NOT EXISTS `request_limiter` (
`id` bigint UNSIGNED AUTO_INCREMENT COMMENT 'Unique identifier for this entry',
`chat_id` char(255) NULL DEFAULT NULL COMMENT 'Unique chat identifier',
......
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