Commit 01827a58 authored by LONGMAN's avatar LONGMAN

Added tests

parent 9bc25ee8
language: php
php:
- 5.3
- 5.4
- 5.5
- 5.6
- 7.0
- hhvm
sudo: false
before_install:
- composer self-update
install:
- travis_retry composer install --no-interaction --prefer-source
script:
- phpunit
- sh -c "if [ '$TRAVIS_PHP_VERSION' != '7.0' ]; then vendor/bin/phpcs --report=full --extensions=php -p --standard=build/phpcs .; fi"
matrix:
allow_failures:
- php: hhvm
- php: 7.0
fast_finish: true
notifications:
on_success: never
on_failure: always
\ No newline at end of file
...@@ -59,6 +59,8 @@ Instructions ...@@ -59,6 +59,8 @@ Instructions
## Installation ## Installation
You need server with https and composer support. You need server with https and composer support.
Install this package through [Composer](https://getcomposer.org/). Edit your project's `composer.json` file to require `longman/telegram-bot`.
Create composer.json file: Create composer.json file:
```js ```js
{ {
...@@ -70,9 +72,13 @@ Create composer.json file: ...@@ -70,9 +72,13 @@ Create composer.json file:
} }
} }
``` ```
And run composer update And run composer update
**Or** run a command in your command line:
```
composer require longman/telegram-bot
```
###### bot token ###### bot token
You will notice that the Telegram Bot wants a value for `API_KEY`. This token may be obtained via a telegram client for your bot. See [this](https://core.telegram.org/bots#botfather) link if you are unsure of how to so this. You will notice that the Telegram Bot wants a value for `API_KEY`. This token may be obtained via a telegram client for your bot. See [this](https://core.telegram.org/bots#botfather) link if you are unsure of how to so this.
...@@ -90,13 +96,19 @@ $loader = require __DIR__.'/vendor/autoload.php'; ...@@ -90,13 +96,19 @@ $loader = require __DIR__.'/vendor/autoload.php';
$API_KEY = 'your_bot_api_key'; $API_KEY = 'your_bot_api_key';
$BOT_NAME = 'namebot'; $BOT_NAME = 'namebot';
// create Telegram API object try {
$telegram = new Longman\TelegramBot\Telegram($API_KEY,$BOT_NAME); // create Telegram API object
$telegram = new Longman\TelegramBot\Telegram($API_KEY, $BOT_NAME);
// set webhook
echo $telegram->setWebHook('https://yourdomain/yourpath_to_hook.php');
// set webhook
echo $telegram->setWebHook('https://yourdomain/yourpath_to_hook.php');
}
catch (Longman\TelegramBot\Exception\TelegramException $e) {
echo $e->getMessage();
}
``` ```
And open your set.php via browser
After create hook.php and put: After create hook.php and put:
```php ```php
...@@ -106,12 +118,18 @@ $loader = require __DIR__.'/vendor/autoload.php'; ...@@ -106,12 +118,18 @@ $loader = require __DIR__.'/vendor/autoload.php';
$API_KEY = 'your_bot_api_key'; $API_KEY = 'your_bot_api_key';
$BOT_NAME = 'namebot'; $BOT_NAME = 'namebot';
// create Telegram API object
$telegram = new Longman\TelegramBot\Telegram($API_KEY,$BOT_NAME);
// handle telegram webhook request try {
$telegram->handle(); // create Telegram API object
$telegram = new Longman\TelegramBot\Telegram($API_KEY,$BOT_NAME);
// handle telegram webhook request
$telegram->handle();
}
catch (Longman\TelegramBot\Exception\TelegramException $e) {
// log telegram errors
// echo $e->getMessage();
}
``` ```
If you want insert in database messages for further usage in commands, create database and import structure.sql and enable mysql support after object creation and BEFORE handle method If you want insert in database messages for further usage in commands, create database and import structure.sql and enable mysql support after object creation and BEFORE handle method
......
{ {
"name": "longman/telegram-bot", "name": "longman/telegram-bot",
"type": "library", "type": "library",
"description": "PHP telegram bot", "description": "PHP telegram bot",
"keywords": ["telegram", "bot", "api"], "keywords": ["telegram", "bot", "api"],
"license": "MIT", "license": "MIT",
"homepage": "https://github.com/akalongman/php-telegram-bot", "homepage": "https://github.com/akalongman/php-telegram-bot",
"support": { "support": {
"issues": "https://github.com/akalongman/php-telegram-bot/issues", "issues": "https://github.com/akalongman/php-telegram-bot/issues",
"source": "https://github.com/akalongman/php-telegram-bot" "source": "https://github.com/akalongman/php-telegram-bot"
}, },
"authors": [ "authors": [
{ {
"name": "Avtandil Kikabidze aka LONGMAN", "name": "Avtandil Kikabidze aka LONGMAN",
"email": "akalongman@gmail.com", "email": "akalongman@gmail.com",
"homepage": "http://longman.ge", "homepage": "http://longman.ge",
"role": "Developer" "role": "Developer"
} }
], ],
"require": { "require": {
"php": ">=5.3.0", "php": ">=5.3.0",
"ext-pdo": "*", "ext-pdo": "*",
"hoa/math":"~0.0" "hoa/math": "~0.0"
},
}, "autoload": {
"autoload": { "psr-4": {
"psr-4": { "Longman\\TelegramBot\\": "src/"
"Longman\\TelegramBot\\": "src/" }
} },
}, "autoload-dev": {
"autoload-dev": { "psr-4": {
"psr-4": { "Tests\\": "tests/"
"Tests\\": "tests/" }
} },
}, "minimum-stability": "dev",
"minimum-stability": "dev", "require-dev": {
"require-dev": { "phpunit/phpunit": "4.1.*",
"phpunit/phpunit": "4.1.*", "phpspec/phpspec": "~2.1",
"phpspec/phpspec": "~2.1", "squizlabs/php_codesniffer": "2.3.*"
"squizlabs/php_codesniffer": "2.3.*" }
} }
} \ No newline at end of file
This diff is collapsed.
<?xml version="1.0" encoding="UTF-8"?>
<phpunit
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="http://schema.phpunit.de/4.6/phpunit.xsd"
bootstrap="./tests/Bootstrap.php"
backupGlobals="false"
backupStaticAttributes="false"
colors="true"
convertErrorsToExceptions="true"
convertNoticesToExceptions="true"
convertWarningsToExceptions="true"
processIsolation="false"
stopOnError="false"
stopOnFailure="false"
stopOnIncomplete="false"
stopOnSkipped="false"
syntaxCheck="true"
timeoutForLargeTests="60"
timeoutForMediumTests="10"
timeoutForSmallTests="1"
verbose="false"
>
<php>
<ini name="error_reporting" value="-1" />
<const name="PHPUNIT_TESTSUITE" value="true"/>
</php>
<testsuites>
<testsuite name="Package Test Suite">
<directory>./tests/</directory>
</testsuite>
</testsuites>
<logging>
<!-- <log type="coverage-html" target="build/coverage" title="Package" charset="UTF-8" yui="true" highlight="true"
lowUpperBound="35" highLowerBound="70" />
<log type="coverage-clover" target="build/logs/clover.xml" />
<log type="junit" target="build/logs/junit.xml" logIncompleteSkipped="false" />
--> <!--<log type="testdox-html" target="tests/testdox.html" logIncompleteSkipped="false" />-->
</logging>
</phpunit>
...@@ -18,8 +18,11 @@ abstract class Command ...@@ -18,8 +18,11 @@ abstract class Command
protected $message; protected $message;
protected $command; protected $command;
protected $usage = 'Command help text'; protected $description = 'Command help';
protected $usage = 'Command usage';
protected $version = '1.0.0'; protected $version = '1.0.0';
protected $enabled = true;
protected $name = '';
public function __construct(Telegram $telegram) { public function __construct(Telegram $telegram) {
$this->telegram = $telegram; $this->telegram = $telegram;
...@@ -61,8 +64,15 @@ abstract class Command ...@@ -61,8 +64,15 @@ abstract class Command
return $this->version; return $this->version;
} }
public function getHelp() { public function getDescription() {
return $this->getUsage()."\n".$this->getVersion(); return $this->description;
} }
public function getName() {
return $this->name;
}
public function isEnabled() {
return $this->enabled;
}
} }
...@@ -17,6 +17,12 @@ use Longman\TelegramBot\Entities\Update; ...@@ -17,6 +17,12 @@ use Longman\TelegramBot\Entities\Update;
class CalcCommand extends Command class CalcCommand extends Command
{ {
protected $name = 'calc';
protected $description = 'Calculate math expression';
protected $usage = '/calc <expression>';
protected $version = '1.0.0';
protected $enabled = true;
public function execute() { public function execute() {
$update = $this->getUpdate(); $update = $this->getUpdate();
...@@ -34,7 +40,7 @@ class CalcCommand extends Command ...@@ -34,7 +40,7 @@ class CalcCommand extends Command
$data['text'] = $this->compute($text); $data['text'] = $this->compute($text);
$result = Request::sendMessage($data); $result = Request::sendMessage($data);
return $result;
} }
......
...@@ -15,6 +15,13 @@ use Longman\TelegramBot\Entities\Update; ...@@ -15,6 +15,13 @@ use Longman\TelegramBot\Entities\Update;
class DateCommand extends Command class DateCommand extends Command
{ {
protected $name = 'date';
protected $description = 'Show date/time by location';
protected $usage = '/date <location>';
protected $version = '1.0.0';
protected $enabled = true;
private $google_api_key = ''; private $google_api_key = '';
private $base_url = 'https://maps.googleapis.com/maps/api'; private $base_url = 'https://maps.googleapis.com/maps/api';
private $date_format = 'd-m-Y H:i:s'; private $date_format = 'd-m-Y H:i:s';
......
...@@ -15,6 +15,11 @@ use Longman\TelegramBot\Entities\Update; ...@@ -15,6 +15,11 @@ use Longman\TelegramBot\Entities\Update;
class EchoCommand extends Command class EchoCommand extends Command
{ {
protected $name = 'echo';
protected $description = 'Show text';
protected $usage = '/echo <text>';
protected $version = '1.0.0';
protected $enabled = true;
public function execute() { public function execute() {
$update = $this->getUpdate(); $update = $this->getUpdate();
...@@ -32,7 +37,7 @@ class EchoCommand extends Command ...@@ -32,7 +37,7 @@ class EchoCommand extends Command
$result = Request::sendMessage($data); $result = Request::sendMessage($data);
return $result;
} }
......
...@@ -15,8 +15,12 @@ use Longman\TelegramBot\Entities\Update; ...@@ -15,8 +15,12 @@ use Longman\TelegramBot\Entities\Update;
class HelpCommand extends Command class HelpCommand extends Command
{ {
protected $usage = 'Usage: /help <command>'; protected $name = 'help';
protected $description = 'Show bot commands help';
protected $usage = '/help or /help <command>';
protected $version = '1.0.0'; protected $version = '1.0.0';
protected $enabled = true;
public function execute() { public function execute() {
$update = $this->getUpdate(); $update = $this->getUpdate();
...@@ -25,16 +29,42 @@ class HelpCommand extends Command ...@@ -25,16 +29,42 @@ class HelpCommand extends Command
$chat_id = $message->getChat()->getId(); $chat_id = $message->getChat()->getId();
$message_id = $message->getMessageId();
$text = $message->getText(true); $text = $message->getText(true);
$commands = $this->telegram->getCommandsList();
if (empty($text)) {
$msg = 'GeoBot v. '.$this->telegram->getVersion()."\n\n";
$msg .= 'Commands List:'."\n";
foreach($commands as $command) {
if (!$command->isEnabled()) {
continue;
}
$msg .= '/'.$command->getName().' - '.$command->getDescription()."\n";
}
$msg .= "\n".'For exact command help type: /help <command>';
} else {
$text = str_replace('/', '', $text);
if (isset($commands[$text])) {
$command = $commands[$text];
$msg = 'Command: '.$command->getName().' v'.$command->getVersion()."\n";
$msg .= 'Description: '.$command->getDescription()."\n";
$msg .= 'Usage: '.$command->getUsage();
} else {
$msg = 'Command '.$text.' not found';
}
}
$data = array(); $data = array();
$data['chat_id'] = $chat_id; $data['chat_id'] = $chat_id;
$data['text'] = 'GeoBot v. '.VERSION; $data['reply_to_message_id'] = $message_id;
$data['text'] = $msg;
$result = Request::sendMessage($data); $result = Request::sendMessage($data);
return $result;
} }
......
...@@ -15,6 +15,12 @@ use Longman\TelegramBot\Entities\Update; ...@@ -15,6 +15,12 @@ use Longman\TelegramBot\Entities\Update;
class WeatherCommand extends Command class WeatherCommand extends Command
{ {
protected $name = 'weather';
protected $description = 'Show weather by location';
protected $usage = '/weather <location>';
protected $version = '1.0.0';
protected $enabled = true;
private function getWeather($location) { private function getWeather($location) {
$url = 'http://api.openweathermap.org/data/2.5/weather?q='.$location.'&units=metric'; $url = 'http://api.openweathermap.org/data/2.5/weather?q='.$location.'&units=metric';
...@@ -115,6 +121,7 @@ class WeatherCommand extends Command ...@@ -115,6 +121,7 @@ class WeatherCommand extends Command
$result = Request::sendMessage($data); $result = Request::sendMessage($data);
return $result;
} }
......
...@@ -18,6 +18,11 @@ use Longman\TelegramBot\Entities\Update; ...@@ -18,6 +18,11 @@ use Longman\TelegramBot\Entities\Update;
class WhoamiCommand extends Command class WhoamiCommand extends Command
{ {
protected $name = 'whoami';
protected $description = 'Show your id, name and username';
protected $usage = '/whoami';
protected $version = '1.0.0';
protected $enabled = true;
public function execute() { public function execute() {
$update = $this->getUpdate(); $update = $this->getUpdate();
...@@ -38,7 +43,7 @@ class WhoamiCommand extends Command ...@@ -38,7 +43,7 @@ class WhoamiCommand extends Command
$result = Request::sendMessage($data); $result = Request::sendMessage($data);
return $result;
} }
......
...@@ -9,6 +9,7 @@ ...@@ -9,6 +9,7 @@
*/ */
namespace Longman\TelegramBot\Entities; namespace Longman\TelegramBot\Entities;
use Longman\TelegramBot\Exception\TelegramException;
class Chat extends Entity class Chat extends Entity
{ {
...@@ -23,7 +24,7 @@ class Chat extends Entity ...@@ -23,7 +24,7 @@ class Chat extends Entity
$this->id = isset($data['id']) ? $data['id'] : null; $this->id = isset($data['id']) ? $data['id'] : null;
if (empty($this->id)) { if (empty($this->id)) {
throw new \Exception('id is empty!'); throw new TelegramException('id is empty!');
} }
$this->title = isset($data['title']) ? $data['title'] : null; $this->title = isset($data['title']) ? $data['title'] : null;
......
...@@ -10,6 +10,7 @@ ...@@ -10,6 +10,7 @@
namespace Longman\TelegramBot\Entities; namespace Longman\TelegramBot\Entities;
use Longman\TelegramBot\Exception\TelegramException;
class Message extends Entity class Message extends Entity
...@@ -59,32 +60,32 @@ class Message extends Entity ...@@ -59,32 +60,32 @@ class Message extends Entity
protected $_command; protected $_command;
protected $bot_name; protected $bot_name;
public function __construct(array $data,$bot_name) { public function __construct(array $data, $bot_name) {
$this->bot_name = $bot_name; $this->bot_name = $bot_name;
$this->message_id = isset($data['message_id']) ? $data['message_id'] : null; $this->message_id = isset($data['message_id']) ? $data['message_id'] : null;
if (empty($this->message_id)) { if (empty($this->message_id)) {
throw new \Exception('message_id is empty!'); throw new TelegramException('message_id is empty!');
} }
$this->from = isset($data['from']) ? $data['from'] : null; $this->from = isset($data['from']) ? $data['from'] : null;
if (empty($this->from)) { if (empty($this->from)) {
throw new \Exception('from is empty!'); throw new TelegramException('from is empty!');
} }
$this->from = new User($this->from); $this->from = new User($this->from);
$this->date = isset($data['date']) ? $data['date'] : null; $this->date = isset($data['date']) ? $data['date'] : null;
if (empty($this->date)) { if (empty($this->date)) {
throw new \Exception('date is empty!'); throw new TelegramException('date is empty!');
} }
$this->chat = isset($data['chat']) ? $data['chat'] : null; $this->chat = isset($data['chat']) ? $data['chat'] : null;
if (empty($this->chat)) { if (empty($this->chat)) {
throw new Exception('chat is empty!'); throw new TelegramException('chat is empty!');
} }
$this->chat = new Chat($this->chat); $this->chat = new Chat($this->chat);
...@@ -105,12 +106,13 @@ class Message extends Entity ...@@ -105,12 +106,13 @@ class Message extends Entity
} }
} }
//return the entire command like /echo or /echo@bot1 if specified
public function getFullCommand(){
return strtok($this->text, ' ');
} //return the entire command like /echo or /echo@bot1 if specified
public function getFullCommand(){
return strtok($this->text, ' ');
}
public function getCommand() { public function getCommand() {
...@@ -119,20 +121,20 @@ class Message extends Entity ...@@ -119,20 +121,20 @@ class Message extends Entity
} }
$cmd = $this->getFullCommand(); $cmd = $this->getFullCommand();
if (substr($cmd, 0, 1) === '/') { if (substr($cmd, 0, 1) === '/') {
$cmd = substr($cmd, 1); $cmd = substr($cmd, 1);
//check if command is follow by botname //check if command is follow by botname
$split_cmd = explode('@', $cmd); $split_cmd = explode('@', $cmd);
if(isset($split_cmd[1])){ if (isset($split_cmd[1])) {
//command is followed by name check if is addressed to me //command is followed by name check if is addressed to me
if(strtolower($split_cmd[1]) == strtolower($this->bot_name)){ if (strtolower($split_cmd[1]) == strtolower($this->bot_name)){
return $this->_command = $split_cmd[0]; return $this->_command = $split_cmd[0];
} }
}else{ } else {
//command is not followed by name //command is not followed by name
return $this->_command = $cmd; return $this->_command = $cmd;
} }
} }
......
...@@ -9,7 +9,7 @@ ...@@ -9,7 +9,7 @@
*/ */
namespace Longman\TelegramBot\Entities; namespace Longman\TelegramBot\Entities;
use Longman\TelegramBot\Exception\TelegramException;
class Update extends Entity class Update extends Entity
...@@ -17,7 +17,7 @@ class Update extends Entity ...@@ -17,7 +17,7 @@ class Update extends Entity
protected $update_id; protected $update_id;
protected $message; protected $message;
protected $bot_name; protected $bot_name;
...@@ -29,12 +29,12 @@ class Update extends Entity ...@@ -29,12 +29,12 @@ class Update extends Entity
$message = isset($data['message']) ? $data['message'] : null; $message = isset($data['message']) ? $data['message'] : null;
if (empty($update_id)) { if (empty($update_id)) {
throw new \Exception('update_id is empty!'); throw new TelegramException('update_id is empty!');
} }
$this->bot_name = $bot_name; $this->bot_name = $bot_name;
$this->update_id = $update_id; $this->update_id = $update_id;
$this->message = new Message($message,$bot_name); $this->message = new Message($message, $bot_name);
} }
......
...@@ -9,6 +9,7 @@ ...@@ -9,6 +9,7 @@
*/ */
namespace Longman\TelegramBot\Entities; namespace Longman\TelegramBot\Entities;
use Longman\TelegramBot\Exception\TelegramException;
class User extends Entity class User extends Entity
{ {
...@@ -25,12 +26,12 @@ class User extends Entity ...@@ -25,12 +26,12 @@ class User extends Entity
$this->id = isset($data['id']) ? $data['id'] : null; $this->id = isset($data['id']) ? $data['id'] : null;
if (empty($this->id)) { if (empty($this->id)) {
throw new \Exception('id is empty!'); throw new TelegramException('id 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 \Exception('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;
......
<?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\Exception;
class TelegramException extends \Exception
{
}
...@@ -9,6 +9,7 @@ ...@@ -9,6 +9,7 @@
*/ */
namespace Longman\TelegramBot; namespace Longman\TelegramBot;
use Longman\TelegramBot\Exception\TelegramException;
class Request class Request
{ {
...@@ -66,6 +67,10 @@ class Request ...@@ -66,6 +67,10 @@ class Request
public static function send($action, array $data = null) { public static function send($action, array $data = null) {
if (defined('PHPUNIT_TESTSUITE')) {
return $data;
}
$ch = curl_init(); $ch = curl_init();
$curlConfig = array( $curlConfig = array(
CURLOPT_URL => 'https://api.telegram.org/bot'.self::$telegram->getApiKey().'/'.$action, CURLOPT_URL => 'https://api.telegram.org/bot'.self::$telegram->getApiKey().'/'.$action,
...@@ -77,8 +82,6 @@ class Request ...@@ -77,8 +82,6 @@ class Request
if (!empty($data['text']) && substr($data['text'], 0, 1) === '@') { if (!empty($data['text']) && substr($data['text'], 0, 1) === '@') {
$data['text'] = ' '.$data['text']; $data['text'] = ' '.$data['text'];
} }
//$data = array_map('urlencode', $data);
$curlConfig[CURLOPT_POSTFIELDS] = $data; $curlConfig[CURLOPT_POSTFIELDS] = $data;
} }
...@@ -87,7 +90,7 @@ class Request ...@@ -87,7 +90,7 @@ class Request
$result = curl_exec($ch); $result = curl_exec($ch);
curl_close($ch); curl_close($ch);
return $result; return !empty($result) ? json_decode($result, true) : false;
} }
...@@ -95,7 +98,7 @@ class Request ...@@ -95,7 +98,7 @@ class Request
public static function sendMessage(array $data) { public static function sendMessage(array $data) {
if (empty($data)) { if (empty($data)) {
throw new \Exception('Data is empty!'); throw new TelegramException('Data is empty!');
} }
$result = self::send('sendMessage', $data); $result = self::send('sendMessage', $data);
...@@ -103,4 +106,13 @@ class Request ...@@ -103,4 +106,13 @@ class Request
} }
public static function setWebhook($url) {
$result = self::send('setWebhook', array('url'=>$url));
return $result;
}
} }
...@@ -16,20 +16,28 @@ ini_set('memory_limit', -1); ...@@ -16,20 +16,28 @@ ini_set('memory_limit', -1);
date_default_timezone_set('UTC'); date_default_timezone_set('UTC');
define('VERSION', '0.0.2'); define('BASE_PATH', dirname(__FILE__));
use Longman\TelegramBot\Entities\Update; use Longman\TelegramBot\Entities\Update;
use Longman\TelegramBot\Exception\TelegramException;
/** /**
* @package Telegram * @package Telegram
* @author Avtandil Kikabidze <akalongman@gmail.com> * @author Avtandil Kikabidze <akalongman@gmail.com>
* @copyright Avtandil Kikabidze <akalongman@gmail.com> * @copyright Avtandil Kikabidze <akalongman@gmail.com>
* @license http://opensource.org/licenses/mit-license.php The MIT License (MIT) * @license http://opensource.org/licenses/mit-license.php The MIT License (MIT)
* @link http://www.github.com/akalongman/telegram-bot * @link http://www.github.com/akalongman/php-telegram-bot
*/ */
class Telegram class Telegram
{ {
/**
* Version
*
* @var string
*/
protected $version = '0.0.5';
/** /**
* Telegram API key * Telegram API key
* *
...@@ -37,12 +45,12 @@ class Telegram ...@@ -37,12 +45,12 @@ class Telegram
*/ */
protected $api_key = ''; protected $api_key = '';
/** /**
* Telegram API name * Telegram Bot name
* *
* @var string * @var string
*/ */
protected $bot_name = ''; protected $bot_name = '';
/** /**
...@@ -109,9 +117,18 @@ class Telegram ...@@ -109,9 +117,18 @@ class Telegram
* *
* @param string $api_key * @param string $api_key
*/ */
public function __construct($api_key,$bot_name) { public function __construct($api_key, $bot_name) {
if (empty($api_key)) {
throw new TelegramException('API KEY not defined!');
}
if (empty($bot_name)) {
throw new TelegramException('Bot Username not defined!');
}
$this->api_key = $api_key; $this->api_key = $api_key;
$this->bot_name = $bot_name; $this->bot_name = $bot_name;
Request::initialize($this); Request::initialize($this);
} }
...@@ -142,19 +159,41 @@ class Telegram ...@@ -142,19 +159,41 @@ class Telegram
/** /**
* Get commands list * Get commands list
* *
* @return string $update * @return array $commands
*/ */
public function getCommandsList() { public function getCommandsList() {
// iterate files
// getCommandClass
$commands = array();
try {
$files = new \DirectoryIterator(BASE_PATH.'/Commands');
}
catch(\Exception $e) {
throw new TelegramException('Can not open path: '.BASE_PATH.'/Commands');
}
foreach ($files as $fileInfo) {
if ($fileInfo->isDot()) continue;
$name = $fileInfo->getFilename();
$name = strtolower(str_replace('Command.php', '', $name));
$commands[$name] = $this->getCommandClass($name);
}
if (!empty($this->commands_dir)) {
foreach ($this->commands_dir as $dir) {
if (!is_dir($dir)) {
continue;
}
foreach (new \DirectoryIterator($dir) as $fileInfo) {
if ($fileInfo->isDot()) continue;
$name = $fileInfo->getFilename();
$name = strtolower(str_replace('Command.php', '', $name));
$commands[$name] = $this->getCommandClass($name);
}
}
}
return $this->update; return $commands;
} }
...@@ -219,18 +258,19 @@ class Telegram ...@@ -219,18 +258,19 @@ class Telegram
if (empty($this->input)) { if (empty($this->input)) {
throw new \Exception('Input is empty!'); throw new TelegramException('Input is empty!');
} }
$post = json_decode($this->input, true); $post = json_decode($this->input, true);
if (empty($post)) { if (empty($post)) {
throw new \Exception('Invalid JSON!'); throw new TelegramException('Invalid JSON!');
} }
$update = new Update($post,$this->bot_name);
$update = new Update($post, $this->bot_name);
$this->insertRequest($update); $this->insertRequest($update);
...@@ -262,7 +302,7 @@ class Telegram ...@@ -262,7 +302,7 @@ class Telegram
* *
* @return object * @return object
*/ */
protected function getCommandClass($command, Update $update = null) { public function getCommandClass($command, Update $update = null) {
$this->commands_dir = array_unique($this->commands_dir); $this->commands_dir = array_unique($this->commands_dir);
$this->commands_dir = array_reverse($this->commands_dir); $this->commands_dir = array_reverse($this->commands_dir);
$class_name = ucfirst($command).'Command'; $class_name = ucfirst($command).'Command';
...@@ -355,7 +395,7 @@ class Telegram ...@@ -355,7 +395,7 @@ class Telegram
} }
catch(PDOException $e) { catch(PDOException $e) {
throw new \Exception($e->getMessage()); throw new TelegramException($e->getMessage());
} }
...@@ -370,9 +410,10 @@ class Telegram ...@@ -370,9 +410,10 @@ class Telegram
*/ */
public function addCommandsPath($folder) { public function addCommandsPath($folder) {
if (!is_dir($folder)) { if (!is_dir($folder)) {
throw new \Exception('Commands folder not exists!'); throw new TelegramException('Commands folder not exists!');
} }
$this->commands_dir[] = $folder; $this->commands_dir[] = $folder;
return $this;
} }
/** /**
...@@ -384,14 +425,23 @@ class Telegram ...@@ -384,14 +425,23 @@ class Telegram
return $this->api_key; return $this->api_key;
} }
/** /**
* Get BOT NAME * Get BOT NAME
* *
* @return string * @return string
*/ */
public function getBotName() { public function getBotName() {
return $this->bot_name; return $this->bot_name;
} }
/**
* Get Version
*
* @return string
*/
public function getVersion() {
return $this->version;
}
/** /**
* Set Webhook for bot * Set Webhook for bot
...@@ -399,7 +449,16 @@ class Telegram ...@@ -399,7 +449,16 @@ class Telegram
* @return string * @return string
*/ */
public function setWebHook($url){ public function setWebHook($url){
return Request::send('setWebhook', array('url'=>$url)); if (empty($url)) {
throw new TelegramException('Hook url is empty!');
}
$result = Request::setWebhook($url);
if (!$result['ok']) {
throw new TelegramException('Webhook was not set! Error: '.$result['description']);
}
return $result['description'];
} }
...@@ -412,7 +471,7 @@ class Telegram ...@@ -412,7 +471,7 @@ class Telegram
*/ */
public function enableMySQL(array $credentials){ public function enableMySQL(array $credentials){
if (empty($credentials)) { if (empty($credentials)) {
throw new \Exception('MySQL credentials not provided!'); throw new TelegramException('MySQL credentials not provided!');
} }
$this->mysql_credentials = $credentials; $this->mysql_credentials = $credentials;
...@@ -425,7 +484,7 @@ class Telegram ...@@ -425,7 +484,7 @@ class Telegram
$pdo->setAttribute (\PDO::ATTR_ERRMODE, \PDO::ERRMODE_WARNING); $pdo->setAttribute (\PDO::ATTR_ERRMODE, \PDO::ERRMODE_WARNING);
} }
catch (\PDOException $e) { catch (\PDOException $e) {
throw new \Exception($e->getMessage()); throw new TelegramException($e->getMessage());
} }
$this->pdo = $pdo; $this->pdo = $pdo;
......
<?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 Tests;
/*
* Set error reporting to the max level.
*/
error_reporting(-1);
/*
* Set UTC timezone.
*/
date_default_timezone_set('UTC');
$root = realpath(dirname(dirname(__FILE__)));
/**
* Check that --dev composer installation was done
*/
if (!file_exists($root . '/vendor/autoload.php')) {
throw new Exception(
'Please run "php composer.phar install --dev" in root directory '
. 'to setup unit test dependencies before running the tests'
);
}
// Include the Composer autoloader
$loader = require __DIR__ . '/../vendor/autoload.php';
/*
* Unset global variables that are no longer needed.
*/
unset($root, $loader);
<?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 Tests\Unit\Commands;
use \Tests\Unit\TestCase;
use \Longman\TelegramBot\Telegram;
class CalcCommandTest extends TestCase
{
/**
* @var \Longman\TelegramBot\Telegram
*/
private $telegram;
/**
* @var int
*/
private $message_id = 1;
/**
* @var int
*/
private $chat_id = 2;
/**
* setUp
*/
protected function setUp()
{
$this->telegram = new Telegram('testapikey', 'testbotname');
$msg = '\/calc 2+2';
$update = '{"update_id":'.(int)microtime(true).',"message":{"message_id":'.$this->message_id.',"from":{"id":100000,"first_name":"Avtandil","last_name":"Kikabidze","username":"LONGMAN"},"chat":{"id":'.$this->chat_id.',"first_name":"Avtandil","last_name":"Kikabidze","username":"LONGMAN"},"date":1435507990,"text":"'.$msg.'"}}';
$this->telegram->setCustomUpdate($update);
}
/**
* @test
*/
public function execute() {
$result = $this->telegram->handle();
$this->assertEquals('4', $result['text']);
$this->assertEquals($this->message_id, $result['reply_to_message_id']);
$this->assertEquals($this->chat_id, $result['chat_id']);
}
}
<?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 Tests\Unit;
use \Longman\TelegramBot\Telegram;
/**
* @package TelegramTest
* @author Avtandil Kikabidze <akalongman@gmail.com>
* @copyright Avtandil Kikabidze <akalongman@gmail.com>
* @license http://opensource.org/licenses/mit-license.php The MIT License (MIT)
* @link http://www.github.com/akalongman/php-telegram-bot
*/
class TelegramTest extends TestCase
{
/**
* @var \Longman\TelegramBot\Telegram
*/
private $telegram;
/**
* setUp
*/
protected function setUp()
{
$this->telegram = new Telegram('testapikey', 'testbotname');
}
/**
* @test
* @expectedException \Longman\TelegramBot\Exception\TelegramException
*/
public function newInstanceWithoutParams() {
$telegram = new Telegram('testapikey', null);
$telegram = new Telegram(null, 'test');
}
/**
* @test
*/
public function getCommandsList() {
$commands = $this->telegram->getCommandsList();
$this->assertInternalType('array', $commands);
$this->assertNotCount(0, $commands);
}
/**
* @test
*/
public function getCommandsClass() {
$command = $this->telegram->getCommandClass('help');
$this->assertInstanceOf('Longman\TelegramBot\Commands\HelpCommand', $command);
}
/**
* @test
*/
public function getApiKey() {
$this->assertEquals('testapikey', $this->telegram->getApiKey());
}
/**
* @test
*/
public function getBotName() {
$this->assertEquals('testbotname', $this->telegram->getBotName());
}
}
<?php
namespace Tests\Unit;
class TestCase extends \PHPUnit_Framework_TestCase
{
protected function skip64BitTest()
{
if (PHP_INT_SIZE == 4) {
$this->markTestSkipped(
'Skipping test that can run only on a 64-bit build of PHP.'
);
}
}
}
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