Skip to content

Commit

Permalink
Merge pull request #3 from MBoretto/conflict
Browse files Browse the repository at this point in the history
Conflict
  • Loading branch information
jacklul committed May 23, 2016
2 parents 09d4337 + 307c4ce commit 15afa62
Show file tree
Hide file tree
Showing 44 changed files with 863 additions and 188 deletions.
5 changes: 5 additions & 0 deletions CREDITS
Original file line number Diff line number Diff line change
Expand Up @@ -21,3 +21,8 @@ N: Armando Lüscher
E: armando@noplanman.ch
W: http://noplanman.ch
D: Maintainer and Collaborator

N: Jack'lul (alias)
E: jacklul@jacklul.com
W: http://jacklul.com
D: Maintainer and Collaborator
22 changes: 22 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ A Telegram Bot based on the official [Telegram Bot API](https://core.telegram.or
- [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)
Expand Down Expand Up @@ -401,6 +402,27 @@ $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:

```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:

```Botan::shortenUrl('https://github.com/akalongman/php-telegram-bot', $user_id);```

Shortened URLs are cached in the database (if MySQL storage is enabled).

### Commands

#### Predefined Commands
Expand Down
107 changes: 11 additions & 96 deletions examples/Commands/InlinekeyboardCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
use Longman\TelegramBot\Commands\UserCommand;
use Longman\TelegramBot\Request;
use Longman\TelegramBot\Entities\InlineKeyboardMarkup;
use Longman\TelegramBot\Entities\InlineKeyboardButton;

/**
* User "/inlinekeyboard" command
Expand All @@ -22,8 +23,8 @@ class InlinekeyboardCommand extends UserCommand
/**#@+
* {@inheritdoc}
*/
protected $name = 'inlinekeyboard';
protected $description = 'Show a custom inline keybord with reply markup';
protected $name = 'Inlinekeyboard';
protected $description = 'Show inline keyboard';
protected $usage = '/inlinekeyboard';
protected $version = '0.0.1';
/**#@-*/
Expand All @@ -34,104 +35,18 @@ class InlinekeyboardCommand extends UserCommand
public function execute()
{
$message = $this->getMessage();
$chat_id = $message->getChat()->getId();
$text = $message->getText(true);

$data = [];
$data['chat_id'] = $chat_id;
$data['text'] = 'Press a Button:';

//Keyboard examples
$inline_keyboards = [];

//0
$inline_keyboard[] = [
[
'text' => '<',
'callback_data' => 'go_left'
],
[
'text' => '^',
'callback_data' => 'go_up'
],
[
'text' => '>',
'callback_data' => 'go_right'
]
];

$inline_keyboards[] = $inline_keyboard;
unset($inline_keyboard);

//1
$inline_keyboard[] = [
[
'text' => 'open google.com',
'url' => 'google.com'
],
[
'text' => 'open youtube.com',
'url' => 'youtube.com'
]
];

$inline_keyboards[] = $inline_keyboard;
unset($inline_keyboard);

//2
$inline_keyboard[] = [
[
'text' => 'search \'test\' inline',
'switch_inline_query' => 'test'
],
[
'text' => 'search \'cats\' inline',
'switch_inline_query' => 'cats'
]
$inline_keyboard = [
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']),
];
$inline_keyboard[] = [
[
'text' => 'search \'earth\' inline',
'switch_inline_query' => 'earth'
],
$data = [
'chat_id' => $message->getChat()->getId(),
'text' => 'inline keyboard',
'reply_markup' => new InlineKeyboardMarkup(['inline_keyboard' => [$inline_keyboard]]),
];

$inline_keyboards[] = $inline_keyboard;
unset($inline_keyboard);

//3
$inline_keyboard[] = [
[
'text' => 'open url',
'url' => 'https://github.com/akalongman/php-telegram-bot'
]
];
$inline_keyboard[] = [
[
'text' => 'switch to inline',
'switch_inline_query' => 'thumb up'
]
];
$inline_keyboard[] = [
[
'text' => 'send callback query',
'callback_data' => 'thumb up'
],
[
'text' => 'send callback query (no alert)',
'callback_data' => 'thumb down'
]
];

$inline_keyboards[] = $inline_keyboard;
unset($inline_keyboard);

$data['reply_markup'] = new InlineKeyboardMarkup(
[
'inline_keyboard' => $inline_keyboards[3],
]
);

return Request::sendMessage($data);
}
}
3 changes: 3 additions & 0 deletions examples/getUpdatesCLI.php
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,9 @@
//$telegram->setDownloadPath('../Download');
//$telegram->setUploadPath('../Upload');

//// Botan.io integration
//$telegram->enableBotan('your_token');

// Handle telegram getUpdate request
$ServerResponse = $telegram->handleGetUpdates();

Expand Down
3 changes: 3 additions & 0 deletions examples/hook.php
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,9 @@
//$telegram->setDownloadPath('../Download');
//$telegram->setUploadPath('../Upload');

//// Botan.io integration
//$telegram->enableBotan('your_token');

// Handle telegram webhook request
$telegram->handle();
} catch (Longman\TelegramBot\Exception\TelegramException $e) {
Expand Down
175 changes: 175 additions & 0 deletions src/Botan.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,175 @@
<?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;
}
}
Loading

0 comments on commit 15afa62

Please sign in to comment.