Skip to content

Commit

Permalink
Merge branch 'develop' into limiter_test
Browse files Browse the repository at this point in the history
# Conflicts:
#	src/Telegram.php
  • Loading branch information
jacklul committed Jan 21, 2017
2 parents 0dee13b + 518e9dd commit fc49483
Show file tree
Hide file tree
Showing 18 changed files with 468 additions and 112 deletions.
2 changes: 1 addition & 1 deletion examples/Commands/ShortenerCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ public function execute()
$data = [];
$data['chat_id'] = $chat_id;

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

$data['text'] = $text;

Expand Down
74 changes: 74 additions & 0 deletions examples/cron.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
<?php
/**
* README
* This configuration file is intended to run your commands with crontab.
* Uncommented parameters must be filled
*/

// Load composer
require __DIR__ . '/vendor/autoload.php';

// Add you bot's API key and name
$API_KEY = 'your_bot_api_key';
$BOT_NAME = 'username_bot';

// Define a path for your custom commands
//$commands_path = __DIR__ . '/Commands/';

// Enter your MySQL database credentials
//$mysql_credentials = [
// 'host' => 'localhost',
// 'user' => 'dbuser',
// 'password' => 'dbpass',
// 'database' => 'dbname',
//];

// Your command(s) to run, pass it just like in a message (arguments supported)
$commands = ['/whoami', '/echo I\'m a bot!'];

try {
// Create Telegram API object
$telegram = new Longman\TelegramBot\Telegram($API_KEY, $BOT_NAME);

// Error, Debug and Raw Update logging
//Longman\TelegramBot\TelegramLog::initialize($your_external_monolog_instance);
//Longman\TelegramBot\TelegramLog::initErrorLog($path . '/' . $BOT_NAME . '_error.log');
//Longman\TelegramBot\TelegramLog::initDebugLog($path . '/' . $BOT_NAME . '_debug.log');
//Longman\TelegramBot\TelegramLog::initUpdateLog($path . '/' . $BOT_NAME . '_update.log');

// Enable MySQL
//$telegram->enableMySql($mysql_credentials);

// Enable MySQL with table prefix
//$telegram->enableMySql($mysql_credentials, $BOT_NAME . '_');

// Add an additional commands path
//$telegram->addCommandsPath($commands_path);

// Enable admin user(s)
//$telegram->enableAdmin(your_telegram_id);
//$telegram->enableAdmins([your_telegram_id, other_telegram_id]);

// Add the channel you want to manage
//$telegram->setCommandConfig('sendtochannel', ['your_channel' => '@type_here_your_channel']);

// Here you can set some command specific parameters,
// for example, google geocode/timezone api key for /date command:
//$telegram->setCommandConfig('date', ['google_api_key' => 'your_google_api_key_here']);

// Set custom Upload and Download path
//$telegram->setDownloadPath('../Download');
//$telegram->setUploadPath('../Upload');

// Run user selected commands
$telegram->runCommands($commands);
} catch (Longman\TelegramBot\Exception\TelegramException $e) {
// Silence is golden!
//echo $e;
// Log telegram errors
Longman\TelegramBot\TelegramLog::error($e);
} catch (Longman\TelegramBot\Exception\TelegramLogException $e) {
// Silence is golden!
// Uncomment this to catch log initilization errors
//echo $e;
}
114 changes: 57 additions & 57 deletions src/Botan.php
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ public static function initializeBotan($token, array $options = [])
}

$options_default = [
'timeout' => 3
'timeout' => 3,
];

$options = array_merge($options_default, $options);
Expand All @@ -78,7 +78,7 @@ public static function initializeBotan($token, array $options = [])
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' => $options['timeout']]);

BotanDB::initializeBotanDb();
Expand All @@ -101,8 +101,8 @@ public static function lock($command = '')
/**
* Track function
*
* @param \Longman\TelegramBot\Entities\Update $update
* @param string $command
* @param \Longman\TelegramBot\Entities\Update $update
* @param string $command
*
* @return bool|string
* @throws \Longman\TelegramBot\Exception\TelegramException
Expand All @@ -115,7 +115,7 @@ public static function track(Update $update, $command = '')
return false;
}

if (empty($update)) {
if ($update === null) {
throw new TelegramException('Update object is empty!');
}

Expand All @@ -127,85 +127,83 @@ public static function track(Update $update, $command = '')
$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',
'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'
'callback_query' => 'Callback Query',
];

if (array_key_exists($update_type, $update_object_names)) {
$data = $update_data[$update_type];
$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;
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!");
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;

$result = null;

try {
$response = self::$client->post(
str_replace(
['#TOKEN', '#UID', '#NAME'],
[self::$token, $uid, urlencode($event_name)],
'/track?token=#TOKEN&uid=#UID&name=#NAME'
sprintf(
'/track?token=%1$s&uid=%2$s&name=%3$s',
self::$token,
$uid,
urlencode($event_name)
),
[
'headers' => [
'Content-Type' => 'application/json'
'Content-Type' => 'application/json',
],
'json' => $data
'json' => $data,
]
);

$result = (string) $response->getBody();
} catch (RequestException $e) {
$result = $e->getMessage();
} finally {
$responseData = json_decode($result, true);
}

if ($responseData['status'] !== 'accepted') {
TelegramLog::debug('Botan.io stats report failed: ' . ($result ?: 'empty response') . "\n\n");
$responseData = json_decode($result, true);

return false;
}
if (!$responseData || $responseData['status'] !== 'accepted') {
TelegramLog::debug('Botan.io stats report failed: %s', $result ?: 'empty response');

return $responseData;
return false;
}

return $responseData;
}

/**
* Url Shortener function
*
* @param string $url
* @param integer $user_id
* @param string $url
* @param integer $user_id
*
* @return string
* @throws \Longman\TelegramBot\Exception\TelegramException
Expand All @@ -226,25 +224,27 @@ public static function shortenUrl($url, $user_id)

try {
$response = self::$client->post(
str_replace(
['#TOKEN', '#UID', '#URL'],
[self::$token, $user_id, urlencode($url)],
'/s/?token=#TOKEN&user_ids=#UID&url=#URL'
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();
} finally {
if (filter_var($result, FILTER_VALIDATE_URL) !== false) {
BotanDB::insertShortUrl($url, $user_id, $result);
return $result;
} else {
TelegramLog::debug('Botan.io URL shortening failed for \'' . $url . '\': ' . ($result ?: 'empty response') . "\n\n");

return $url;
}
}

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;
}
}
Loading

0 comments on commit fc49483

Please sign in to comment.