Commit 3228a654 authored by Armando Lüscher's avatar Armando Lüscher Committed by GitHub

Merge pull request #457 from jacklul/misc

Misc additions/changes
parents 036bac23 b3a7d3e2
...@@ -14,7 +14,7 @@ require __DIR__ . '/vendor/autoload.php'; ...@@ -14,7 +14,7 @@ require __DIR__ . '/vendor/autoload.php';
// Add you bot's API key and name // Add you bot's API key and name
$API_KEY = 'your_bot_api_key'; $API_KEY = 'your_bot_api_key';
$BOT_NAME = 'username_bot'; $BOT_USERNAME = 'username_bot';
// Define a path for your custom commands // Define a path for your custom commands
//$commands_path = __DIR__ . '/Commands/'; //$commands_path = __DIR__ . '/Commands/';
...@@ -29,7 +29,7 @@ $mysql_credentials = [ ...@@ -29,7 +29,7 @@ $mysql_credentials = [
try { try {
// Create Telegram API object // Create Telegram API object
$telegram = new Longman\TelegramBot\Telegram($API_KEY, $BOT_NAME); $telegram = new Longman\TelegramBot\Telegram($API_KEY, $BOT_USERNAME);
// Error, Debug and Raw Update logging // Error, Debug and Raw Update logging
//Longman\TelegramBot\TelegramLog::initialize($your_external_monolog_instance); //Longman\TelegramBot\TelegramLog::initialize($your_external_monolog_instance);
......
...@@ -13,7 +13,7 @@ require __DIR__ . '/vendor/autoload.php'; ...@@ -13,7 +13,7 @@ require __DIR__ . '/vendor/autoload.php';
// Add you bot's API key and name // Add you bot's API key and name
$API_KEY = 'your_bot_api_key'; $API_KEY = 'your_bot_api_key';
$BOT_NAME = 'username_bot'; $BOT_USERNAME = 'username_bot';
// Define a path for your custom commands // Define a path for your custom commands
//$commands_path = __DIR__ . '/Commands/'; //$commands_path = __DIR__ . '/Commands/';
...@@ -28,7 +28,7 @@ $BOT_NAME = 'username_bot'; ...@@ -28,7 +28,7 @@ $BOT_NAME = 'username_bot';
try { try {
// Create Telegram API object // Create Telegram API object
$telegram = new Longman\TelegramBot\Telegram($API_KEY, $BOT_NAME); $telegram = new Longman\TelegramBot\Telegram($API_KEY, $BOT_USERNAME);
// Error, Debug and Raw Update logging // Error, Debug and Raw Update logging
//Longman\TelegramBot\TelegramLog::initialize($your_external_monolog_instance); //Longman\TelegramBot\TelegramLog::initialize($your_external_monolog_instance);
......
...@@ -3,11 +3,12 @@ ...@@ -3,11 +3,12 @@
require __DIR__ . '/vendor/autoload.php'; require __DIR__ . '/vendor/autoload.php';
$API_KEY = 'your_bot_api_key'; $API_KEY = 'your_bot_api_key';
$BOT_NAME = 'username_bot'; $BOT_USERNAME = 'username_bot';
$hook_url = 'https://yourdomain/path/to/hook.php'; $hook_url = 'https://yourdomain/path/to/hook.php';
try { try {
// Create Telegram API object // Create Telegram API object
$telegram = new Longman\TelegramBot\Telegram($API_KEY, $BOT_NAME); $telegram = new Longman\TelegramBot\Telegram($API_KEY, $BOT_USERNAME);
// Set webhook // Set webhook
$result = $telegram->setWebhook($hook_url); $result = $telegram->setWebhook($hook_url);
......
...@@ -3,10 +3,11 @@ ...@@ -3,10 +3,11 @@
require __DIR__ . '/vendor/autoload.php'; require __DIR__ . '/vendor/autoload.php';
$API_KEY = 'your_bot_api_key'; $API_KEY = 'your_bot_api_key';
$BOT_NAME = 'username_bot'; $BOT_USERNAME = 'username_bot';
try { try {
// Create Telegram API object // Create Telegram API object
$telegram = new Longman\TelegramBot\Telegram($API_KEY, $BOT_NAME); $telegram = new Longman\TelegramBot\Telegram($API_KEY, $BOT_USERNAME);
// Delete webhook // Delete webhook
$result = $telegram->deleteWebhook(); $result = $telegram->deleteWebhook();
......
...@@ -12,6 +12,7 @@ namespace Longman\TelegramBot\Entities; ...@@ -12,6 +12,7 @@ namespace Longman\TelegramBot\Entities;
use Exception; use Exception;
use Longman\TelegramBot\Entities\InlineQuery\InlineEntity; use Longman\TelegramBot\Entities\InlineQuery\InlineEntity;
use Longman\TelegramBot\TelegramLog;
use ReflectionObject; use ReflectionObject;
/** /**
...@@ -21,22 +22,22 @@ use ReflectionObject; ...@@ -21,22 +22,22 @@ use ReflectionObject;
* *
* @link https://core.telegram.org/bots/api#available-types * @link https://core.telegram.org/bots/api#available-types
* *
* @method array getRawData() Get the raw data passed to this entity * @method array getRawData() Get the raw data passed to this entity
* @method string getBotName() Return the bot name passed to this entity * @method string getBotUsername() Return the bot name passed to this entity
*/ */
abstract class Entity abstract class Entity
{ {
/** /**
* Entity constructor. * Entity constructor.
* *
* @todo Get rid of the $bot_name, it shouldn't be here! * @todo Get rid of the $bot_username, it shouldn't be here!
* *
* @param array $data * @param array $data
* @param string $bot_name * @param string $bot_username
* *
* @throws \Longman\TelegramBot\Exception\TelegramException * @throws \Longman\TelegramBot\Exception\TelegramException
*/ */
public function __construct($data, $bot_name = '') public function __construct($data, $bot_username = '')
{ {
//Make sure we're not raw_data inception-ing //Make sure we're not raw_data inception-ing
if (array_key_exists('raw_data', $data)) { if (array_key_exists('raw_data', $data)) {
...@@ -47,7 +48,7 @@ abstract class Entity ...@@ -47,7 +48,7 @@ abstract class Entity
$data['raw_data'] = $data; $data['raw_data'] = $data;
} }
$data['bot_name'] = $bot_name; $data['bot_username'] = $bot_username;
$this->assignMemberVariables($data); $this->assignMemberVariables($data);
$this->validate(); $this->validate();
} }
...@@ -142,7 +143,7 @@ abstract class Entity ...@@ -142,7 +143,7 @@ abstract class Entity
$sub_entities = $this->subEntities(); $sub_entities = $this->subEntities();
if (isset($sub_entities[$property_name])) { if (isset($sub_entities[$property_name])) {
return new $sub_entities[$property_name]($property, $this->getProperty('bot_name')); return new $sub_entities[$property_name]($property, $this->getProperty('bot_username'));
} }
return $property; return $property;
...@@ -241,4 +242,17 @@ abstract class Entity ...@@ -241,4 +242,17 @@ abstract class Entity
return ($is_username ? '@' : '') . $name; return ($is_username ? '@' : '') . $name;
} }
/**
* Get Bot name
*
* @todo: Left for backwards compatibility, remove in the future
*
* @return string
*/
public function getBotName()
{
TelegramLog::debug('Usage of deprecated method getBotName() detected, please use getBotUsername() instead!');
return $this->getBotUsername();
}
} }
...@@ -79,11 +79,11 @@ class Message extends Entity ...@@ -79,11 +79,11 @@ class Message extends Entity
* Message constructor * Message constructor
* *
* @param array $data * @param array $data
* @param string $bot_name * @param string $bot_username
* *
* @throws \Longman\TelegramBot\Exception\TelegramException * @throws \Longman\TelegramBot\Exception\TelegramException
*/ */
public function __construct(array $data, $bot_name = '') public function __construct(array $data, $bot_username = '')
{ {
//Retro-compatibility //Retro-compatibility
if (isset($data['new_chat_participant'])) { if (isset($data['new_chat_participant'])) {
...@@ -95,7 +95,7 @@ class Message extends Entity ...@@ -95,7 +95,7 @@ class Message extends Entity
unset($data['left_chat_participant']); unset($data['left_chat_participant']);
} }
parent::__construct($data, $bot_name); parent::__construct($data, $bot_username);
} }
/** /**
......
...@@ -21,16 +21,16 @@ class ReplyToMessage extends Message ...@@ -21,16 +21,16 @@ class ReplyToMessage extends Message
* ReplyToMessage constructor. * ReplyToMessage constructor.
* *
* @param array $data * @param array $data
* @param string $bot_name * @param string $bot_username
* *
* @throws \Longman\TelegramBot\Exception\TelegramException * @throws \Longman\TelegramBot\Exception\TelegramException
*/ */
public function __construct(array $data, $bot_name = '') public function __construct(array $data, $bot_username = '')
{ {
//As explained in the documentation //As explained in the documentation
//Reply to message can't contain other reply to message entities //Reply to message can't contain other reply to message entities
unset($data['reply_to_message']); unset($data['reply_to_message']);
parent::__construct($data, $bot_name); parent::__construct($data, $bot_username);
} }
} }
...@@ -26,11 +26,11 @@ class ServerResponse extends Entity ...@@ -26,11 +26,11 @@ class ServerResponse extends Entity
* ServerResponse constructor. * ServerResponse constructor.
* *
* @param array $data * @param array $data
* @param string $bot_name * @param string $bot_username
* *
* @throws \Longman\TelegramBot\Exception\TelegramException * @throws \Longman\TelegramBot\Exception\TelegramException
*/ */
public function __construct(array $data, $bot_name) public function __construct(array $data, $bot_username)
{ {
// Make sure we don't double-save the raw_data // Make sure we don't double-save the raw_data
unset($data['raw_data']); unset($data['raw_data']);
...@@ -41,13 +41,13 @@ class ServerResponse extends Entity ...@@ -41,13 +41,13 @@ class ServerResponse extends Entity
if ($is_ok && is_array($result)) { if ($is_ok && is_array($result)) {
if ($this->isAssoc($result)) { if ($this->isAssoc($result)) {
$data['result'] = $this->createResultObject($result, $bot_name); $data['result'] = $this->createResultObject($result, $bot_username);
} else { } else {
$data['result'] = $this->createResultObjects($result, $bot_name); $data['result'] = $this->createResultObjects($result, $bot_username);
} }
} }
parent::__construct($data, $bot_name); parent::__construct($data, $bot_username);
} }
/** /**
...@@ -88,12 +88,12 @@ class ServerResponse extends Entity ...@@ -88,12 +88,12 @@ class ServerResponse extends Entity
* Create and return the object of the received result * Create and return the object of the received result
* *
* @param array $result * @param array $result
* @param string $bot_name * @param string $bot_username
* *
* @return \Longman\TelegramBot\Entities\Chat|\Longman\TelegramBot\Entities\ChatMember|\Longman\TelegramBot\Entities\File|\Longman\TelegramBot\Entities\Message|\Longman\TelegramBot\Entities\User|\Longman\TelegramBot\Entities\UserProfilePhotos|\Longman\TelegramBot\Entities\WebhookInfo * @return \Longman\TelegramBot\Entities\Chat|\Longman\TelegramBot\Entities\ChatMember|\Longman\TelegramBot\Entities\File|\Longman\TelegramBot\Entities\Message|\Longman\TelegramBot\Entities\User|\Longman\TelegramBot\Entities\UserProfilePhotos|\Longman\TelegramBot\Entities\WebhookInfo
* @throws \Longman\TelegramBot\Exception\TelegramException * @throws \Longman\TelegramBot\Exception\TelegramException
*/ */
private function createResultObject($result, $bot_name) private function createResultObject($result, $bot_username)
{ {
// We don't need to save the raw_data of the response object! // We don't need to save the raw_data of the response object!
$result['raw_data'] = null; $result['raw_data'] = null;
...@@ -115,19 +115,19 @@ class ServerResponse extends Entity ...@@ -115,19 +115,19 @@ class ServerResponse extends Entity
} }
//Response from sendMessage //Response from sendMessage
return new Message($result, $bot_name); return new Message($result, $bot_username);
} }
/** /**
* Create and return the objects array of the received result * Create and return the objects array of the received result
* *
* @param array $result * @param array $result
* @param string $bot_name * @param string $bot_username
* *
* @return null|\Longman\TelegramBot\Entities\ChatMember[]|\Longman\TelegramBot\Entities\Update[] * @return null|\Longman\TelegramBot\Entities\ChatMember[]|\Longman\TelegramBot\Entities\Update[]
* @throws \Longman\TelegramBot\Exception\TelegramException * @throws \Longman\TelegramBot\Exception\TelegramException
*/ */
private function createResultObjects($result, $bot_name) private function createResultObjects($result, $bot_username)
{ {
$results = []; $results = [];
if (isset($result[0]['user'])) { if (isset($result[0]['user'])) {
...@@ -144,7 +144,7 @@ class ServerResponse extends Entity ...@@ -144,7 +144,7 @@ class ServerResponse extends Entity
// We don't need to save the raw_data of the response object! // We don't need to save the raw_data of the response object!
$update['raw_data'] = null; $update['raw_data'] = null;
$results[] = new Update($update, $bot_name); $results[] = new Update($update, $bot_username);
} }
} }
......
...@@ -315,12 +315,12 @@ class Request ...@@ -315,12 +315,12 @@ class Request
{ {
self::ensureValidAction($action); self::ensureValidAction($action);
$bot_name = self::$telegram->getBotName(); $bot_username = self::$telegram->getBotUsername();
if (defined('PHPUNIT_TESTSUITE')) { if (defined('PHPUNIT_TESTSUITE')) {
$fake_response = self::generateGeneralFakeServerResponse($data); $fake_response = self::generateGeneralFakeServerResponse($data);
return new ServerResponse($fake_response, $bot_name); return new ServerResponse($fake_response, $bot_username);
} }
self::ensureNonEmptyData($data); self::ensureNonEmptyData($data);
...@@ -333,7 +333,7 @@ class Request ...@@ -333,7 +333,7 @@ class Request
throw new TelegramException('Telegram returned an invalid response! Please review your bot name and API key.'); throw new TelegramException('Telegram returned an invalid response! Please review your bot name and API key.');
} }
return new ServerResponse($response, $bot_name); return new ServerResponse($response, $bot_username);
} }
/** /**
......
...@@ -40,11 +40,18 @@ class Telegram ...@@ -40,11 +40,18 @@ class Telegram
protected $api_key = ''; protected $api_key = '';
/** /**
* Telegram Bot name * Telegram Bot username
* *
* @var string * @var string
*/ */
protected $bot_name = ''; protected $bot_username = '';
/**
* Telegram Bot id
*
* @var string
*/
protected $bot_id = '';
/** /**
* Raw request data (json) for webhook methods * Raw request data (json) for webhook methods
...@@ -127,22 +134,26 @@ class Telegram ...@@ -127,22 +134,26 @@ class Telegram
* Telegram constructor. * Telegram constructor.
* *
* @param string $api_key * @param string $api_key
* @param string $bot_name * @param string $bot_username
* *
* @throws \Longman\TelegramBot\Exception\TelegramException * @throws \Longman\TelegramBot\Exception\TelegramException
*/ */
public function __construct($api_key, $bot_name) public function __construct($api_key, $bot_username)
{ {
if (empty($api_key)) { if (empty($api_key)) {
throw new TelegramException('API KEY not defined!'); throw new TelegramException('API KEY not defined!');
} }
preg_match('/(\d+)\:[\w\-]+/', $api_key, $matches);
if (!isset($matches[1])) {
throw new TelegramException('Invalid API KEY defined!');
}
$this->bot_id = $matches[1];
$this->api_key = $api_key;
if (empty($bot_name)) { if (empty($bot_username)) {
throw new TelegramException('Bot Username not defined!'); throw new TelegramException('Bot Username not defined!');
} }
$this->bot_username = $bot_username;
$this->api_key = $api_key;
$this->bot_name = $bot_name;
//Set default download and upload path //Set default download and upload path
$this->setDownloadPath(BASE_PATH . '/../Download'); $this->setDownloadPath(BASE_PATH . '/../Download');
...@@ -309,7 +320,7 @@ class Telegram ...@@ -309,7 +320,7 @@ class Telegram
'ok' => false, 'ok' => false,
'description' => 'getUpdates needs MySQL connection!', 'description' => 'getUpdates needs MySQL connection!',
], ],
$this->bot_name $this->bot_username
); );
} }
...@@ -359,7 +370,7 @@ class Telegram ...@@ -359,7 +370,7 @@ class Telegram
throw new TelegramException('Invalid JSON!'); throw new TelegramException('Invalid JSON!');
} }
if ($response = $this->processUpdate(new Update($post, $this->bot_name))) { if ($response = $this->processUpdate(new Update($post, $this->bot_username))) {
return $response->isOk(); return $response->isOk();
} }
...@@ -723,9 +734,32 @@ class Telegram ...@@ -723,9 +734,32 @@ class Telegram
* *
* @return string * @return string
*/ */
public function getBotUsername()
{
return $this->bot_username;
}
/**
* Get Bot name
*
* @todo: Left for backwards compatibility, remove in the future
*
* @return string
*/
public function getBotName() public function getBotName()
{ {
return $this->bot_name; TelegramLog::debug('Usage of deprecated method getBotName() detected, please use getBotUsername() instead!');
return $this->getBotUsername();
}
/**
* Get Bot Id
*
* @return string
*/
public function getBotId()
{
return $this->bot_id;
} }
/** /**
...@@ -828,7 +862,7 @@ class Telegram ...@@ -828,7 +862,7 @@ class Telegram
* Enable Botan.io integration * Enable Botan.io integration
* *
* @param string $token * @param string $token
* @param array $options * @param array $options
* *
* @return \Longman\TelegramBot\Telegram * @return \Longman\TelegramBot\Telegram
* @throws \Longman\TelegramBot\Exception\TelegramException * @throws \Longman\TelegramBot\Exception\TelegramException
...@@ -850,7 +884,7 @@ class Telegram ...@@ -850,7 +884,7 @@ class Telegram
return $this; return $this;
} }
/** /**
* Run provided commands * Run provided commands
* *
...@@ -888,15 +922,15 @@ class Telegram ...@@ -888,15 +922,15 @@ class Telegram
'from' => [ 'from' => [
'id' => $bot_id, 'id' => $bot_id,
'first_name' => $bot_name, 'first_name' => $bot_name,
'username' => $bot_username 'username' => $bot_username,
], ],
'date' => time(), 'date' => time(),
'chat' => [ 'chat' => [
'id' => $bot_id, 'id' => $bot_id,
'type' => 'private', 'type' => 'private',
], ],
'text' => $command 'text' => $command,
] ],
] ]
); );
......
...@@ -51,11 +51,11 @@ class CommandTest extends TestCase ...@@ -51,11 +51,11 @@ class CommandTest extends TestCase
public function setUp() public function setUp()
{ {
//Default command object //Default command object
$this->telegram = new Telegram('apikey', 'testbot'); $this->telegram = new Telegram(self::$dummy_api_key, 'testbot');
$this->command_stub = $this->getMockForAbstractClass($this->command_namespace, [$this->telegram]); $this->command_stub = $this->getMockForAbstractClass($this->command_namespace, [$this->telegram]);
//Create separate command object that contain a command config //Create separate command object that contain a command config
$this->telegram_with_config = new Telegram('apikey', 'testbot'); $this->telegram_with_config = new Telegram(self::$dummy_api_key, 'testbot');
$this->telegram_with_config->setCommandConfig('command_name', ['config_key' => 'config_value']); $this->telegram_with_config->setCommandConfig('command_name', ['config_key' => 'config_value']);
$this->command_stub_with_config = $this->getMockBuilder($this->command_namespace) $this->command_stub_with_config = $this->getMockBuilder($this->command_namespace)
->disableOriginalConstructor() ->disableOriginalConstructor()
......
...@@ -37,7 +37,7 @@ class CommandTestCase extends TestCase ...@@ -37,7 +37,7 @@ class CommandTestCase extends TestCase
*/ */
public function setUp() public function setUp()
{ {
$this->telegram = new Telegram('apikey', 'testbot'); $this->telegram = new Telegram(self::$dummy_api_key, 'testbot');
$this->telegram->addCommandsPath(BASE_COMMANDS_PATH . '/UserCommands'); $this->telegram->addCommandsPath(BASE_COMMANDS_PATH . '/UserCommands');
// Add custom commands dedicated to do some tests. // Add custom commands dedicated to do some tests.
......
...@@ -39,7 +39,7 @@ class ConversationTest extends TestCase ...@@ -39,7 +39,7 @@ class ConversationTest extends TestCase
'password' => PHPUNIT_DB_PASS, 'password' => PHPUNIT_DB_PASS,
]; ];
$this->telegram = new Telegram('apikey', 'testbot'); $this->telegram = new Telegram(self::$dummy_api_key, 'testbot');
$this->telegram->enableMySql($credentials); $this->telegram->enableMySql($credentials);
//Make sure we start with an empty DB for each test. //Make sure we start with an empty DB for each test.
......
...@@ -40,7 +40,7 @@ class TelegramTest extends TestCase ...@@ -40,7 +40,7 @@ class TelegramTest extends TestCase
*/ */
protected function setUp() protected function setUp()
{ {
$this->telegram = new Telegram('apikey', 'testbot'); $this->telegram = new Telegram(self::$dummy_api_key, 'testbot');
// Create a few dummy custom commands paths. // Create a few dummy custom commands paths.
foreach ($this->custom_commands_paths as $custom_path) { foreach ($this->custom_commands_paths as $custom_path) {
...@@ -61,6 +61,7 @@ class TelegramTest extends TestCase ...@@ -61,6 +61,7 @@ class TelegramTest extends TestCase
/** /**
* @expectedException \Longman\TelegramBot\Exception\TelegramException * @expectedException \Longman\TelegramBot\Exception\TelegramException
* @expectedExceptionMessage API KEY not defined!
*/ */
public function testNewInstanceWithoutApiKeyParam() public function testNewInstanceWithoutApiKeyParam()
{ {
...@@ -69,20 +70,30 @@ class TelegramTest extends TestCase ...@@ -69,20 +70,30 @@ class TelegramTest extends TestCase
/** /**
* @expectedException \Longman\TelegramBot\Exception\TelegramException * @expectedException \Longman\TelegramBot\Exception\TelegramException
* @expectedExceptionMessage Invalid API KEY defined!
*/ */
public function testNewInstanceWithoutBotNameParam() public function testNewInstanceWithInvalidApiKeyParam()
{ {
new Telegram('apikey', null); new Telegram('invalid-api-key-format', null);
}
/**
* @expectedException \Longman\TelegramBot\Exception\TelegramException
* @expectedExceptionMessage Bot Username not defined!
*/
public function testNewInstanceWithoutBotUsernameParam()
{
new Telegram(self::$dummy_api_key, null);
} }
public function testGetApiKey() public function testGetApiKey()
{ {
$this->assertEquals('apikey', $this->telegram->getApiKey()); $this->assertEquals(self::$dummy_api_key, $this->telegram->getApiKey());
} }
public function testGetBotName() public function testGetBotUsername()
{ {
$this->assertEquals('testbot', $this->telegram->getBotName()); $this->assertEquals('testbot', $this->telegram->getBotUsername());
} }
public function testEnableAdmins() public function testEnableAdmins()
......
...@@ -12,6 +12,11 @@ namespace Longman\TelegramBot\Tests\Unit; ...@@ -12,6 +12,11 @@ namespace Longman\TelegramBot\Tests\Unit;
class TestCase extends \PHPUnit_Framework_TestCase class TestCase extends \PHPUnit_Framework_TestCase
{ {
/**
* @var string
*/
public static $dummy_api_key = '123456:ABC-DEF1234ghIkl-zyx57W2v1u123ew11';
protected function skip64BitTest() protected function skip64BitTest()
{ {
if (PHP_INT_SIZE === 4) { if (PHP_INT_SIZE === 4) {
......
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