Commit ae4d21ec authored by MBoretto's avatar MBoretto

Merge branch 'master' into hotfix

parents 34634ffa f0db603e
This diff is collapsed.
#!/usr/bin/env php
<?php
#bash script
#while true; do ./getUpdatesCLI.php; done
//Composer Loader
$loader = require __DIR__.'/vendor/autoload.php';
$API_KEY = 'your_bot_api_key';
$BOT_NAME = 'namebot';
//$COMMANDS_FOLDER = __DIR__.'/Commands/';
$credentials = array('host'=>'localhost', 'user'=>'dbuser', 'password'=>'dbpass', 'database'=>'dbname');
try {
// create Telegram API object
$telegram = new Longman\TelegramBot\Telegram($API_KEY, $BOT_NAME);
//Options
$telegram->enableMySQL($credentials);
//$telegram->enableMySQL($credentials, $BOT_NAME.'_');
//$telegram->addCommandsPath($COMMANDS_FOLDER);
//here you can set some command specified parameters,
//for example, google geocode/timezone api key for date command:
//$telegram->setCommandConfig('date', array('google_api_key'=>'your_google_api_key_here'));
//$telegram->setLogRequests(true);
//$telegram->setLogPath($BOT_NAME.'.log');
// handle telegram getUpdate request
$telegram->handleGetUpdates();
} catch (Longman\TelegramBot\Exception\TelegramException $e) {
// log telegram errors
echo $e->getMessage();
}
<?php
//Composer Loader
$loader = require __DIR__.'/vendor/autoload.php';
$API_KEY = 'your_bot_api_key';
$BOT_NAME = 'namebot';
//$COMMANDS_FOLDER = __DIR__.'/Commands/';
//$credentials = array('host'=>'localhost', 'user'=>'dbuser', 'password'=>'dbpass', 'database'=>'dbname');
try {
// create Telegram API object
$telegram = new Longman\TelegramBot\Telegram($API_KEY, $BOT_NAME);
//Options
//$telegram->enableMySQL($credentials);
//$telegram->enableMySQL($credentials, $BOT_NAME.'_');
//$telegram->addCommandsPath($COMMANDS_FOLDER);
// here you can set some command specified parameters,
// for example, google geocode/timezone api key for date command:
//$telegram->setCommandConfig('date', array('google_api_key'=>'your_google_api_key_here'));
//$telegram->setLogRequests(true);
//$telegram->setLogPath($BOT_NAME.'.log');
// handle telegram webhook request
$telegram->handle();
} catch (Longman\TelegramBot\Exception\TelegramException $e) {
// log telegram errors
// echo $e->getMessage();
}
<?php
//Composer Loader
$loader = require __DIR__.'/vendor/autoload.php';
$API_KEY = 'your_bot_api_key';
$BOT_NAME = 'namebot';
try {
// create Telegram API object
$telegram = new Longman\TelegramBot\Telegram($API_KEY, $BOT_NAME);
// set webhook
echo $telegram->setWebHook('https://yourdomain/yourpath_to_hook.php');
} catch (Longman\TelegramBot\Exception\TelegramException $e) {
echo $e->getMessage();
}
......@@ -11,19 +11,33 @@
namespace Longman\TelegramBot\Commands;
use Longman\TelegramBot\Request;
use Longman\TelegramBot\DB;
use Longman\TelegramBot\Command;
use Longman\TelegramBot\Entities\Update;
use Longman\TelegramBot\Exception\TelegramException;
class SendtoallCommand extends Command
{
protected $name = 'sendall';
protected $name = 'sendtoall';
protected $description = 'Send the message to all the user\'s bot';
protected $usage = '/sendall <message to send>';
protected $version = '1.2.0';
protected $enabled = true;
protected $public = true;
//need Mysql
protected $need_mysql = true;
public function executeNoDB()
{
//Database not setted or without connection
//Preparing message
$message = $this->getMessage();
$chat_id = $message->getChat()->getId();
$data = array();
$data['chat_id'] = $chat_id;
$data['text'] = 'Sorry no database connection, unable to execute '.$this->name.' command.';
return Request::sendMessage($data);
}
public function execute()
{
......@@ -37,7 +51,7 @@ class SendtoallCommand extends Command
if (empty($text)) {
$text = 'Write te message to sent: /sendall <message>';
} else {
$results = $this->telegram->sendToActiveChats(
$results = DB::sendToActiveChats(
'sendMessage', //callback function to execute (see Request.php methods)
array('text'=> $text), //Param to evaluate the request
true, //Send to chats (group chat)
......
......@@ -23,6 +23,7 @@ abstract class Command
protected $description = 'Command help';
protected $usage = 'Command usage';
protected $version = '1.0.0';
protected $need_mysql = false;
protected $enabled = true;
protected $name = '';
......@@ -42,8 +43,24 @@ abstract class Command
return $this;
}
public function preExecute()
{
if (!$this->need_mysql |
$this->need_mysql & $this->telegram->isDbEnabled() & DB::isDbConnected()
) {
return $this->execute();
}
return $this->executeNoDB();
}
abstract public function execute();
//this methods is executed if $need_mysql is true but DB connection for some reason is not avaiable
public function executeNoDB()
{
}
public function getUpdate()
{
return $this->update;
......
This diff is collapsed.
......@@ -104,7 +104,7 @@ class Message extends Entity
$this->reply_to_message = isset($data['reply_to_message']) ? $data['reply_to_message'] : null;
if (!empty($this->reply_to_message)) {
$this->reply_to_message = new self($this->reply_to_message);
$this->reply_to_message = new Message($this->reply_to_message, $this->bot_name);
}
$this->new_chat_participant = isset($data['new_chat_participant']) ? $data['new_chat_participant'] : null;
......
......@@ -22,29 +22,52 @@ class ServerResponse extends Entity
protected $error_code;
protected $description;
public function __construct(array $data, $bot_name)
{
if (isset($data['ok']) & isset($data['result'])) {
if ($data['ok'] & $data['result'] != 1) {
//Response from sendMessage set
$this->ok = $data['ok'];
$this->result = new Message($data['result'], $bot_name);
$this->error_code = null;
$this->description = null;
} elseif ($data['ok'] & $data['result'] == 1) {
//Response from setWebhook set
$this->ok = $data['ok'];
$this->result = $data['result'];
$this->error_code = null;
$this->description = $data['description'];
if (is_array($data['result'])) {
if ($data['ok'] & !$this->isAssoc($data['result'])) {
//update id
$this->ok = $data['ok'];
//$this->result =[];
foreach ($data['result'] as $update) {
$this->result[] = new Update($update, $bot_name);
}
$this->error_code = null;
$this->description = null;
} elseif ($data['ok'] & $this->isAssoc($data['result'])) {
//Response from sendMessage set
$this->ok = $data['ok'];
$this->result = new Message($data['result'], $bot_name);
$this->error_code = null;
$this->description = null;
}
} else {
$this->ok = false;
$this->result = null;
$this->error_code = $data['error_code'];
$this->description = $data['description'];
if ($data['ok'] & $data['result'] == true) {
//Response from setWebhook set
$this->ok = $data['ok'];
$this->result = true;
$this->error_code = null;
if (isset($data['description'])) {
$this->description = $data['description'];
} else {
$this->description = '';
}
} else {
$this->ok = false;
$this->result = null;
$this->error_code = $data['error_code'];
$this->description = $data['description'];
}
}
} else {
//webHook not set
$this->ok = false;
......@@ -67,10 +90,15 @@ class ServerResponse extends Entity
$this->description = null;
}
//throw new TelegramException('ok(variable) is not set!');
//throw new TelegramException('ok(variable) is not set!');
}
}
//must be an array
protected function isAssoc(array $array)
{
return (bool)count(array_filter(array_keys($array), 'is_string'));
}
public function isOk()
{
return $this->ok;
......@@ -87,45 +115,4 @@ class ServerResponse extends Entity
{
return $this->description;
}
//Succes request
//Array
//(
// [ok] => 1
// [result] => Array
// (
// [message_id] => 3582
// [from] => Array
// (
// [id] => 12345678
// [first_name] => name
// [username] => botname
// )
//
// [chat] => Array
// (
// [id] => 123456789
// [first_name] => name
// [username] => Surname
// )
//
// [date] => 1441194780
// [text] => hello
// )
//
//)
// Error Request
//
//Array
//(
// [ok] =>
// [error_code] => 401
// [description] => Error: Unauthorized
//)
//Array
//(
// [chat_id] => 110751663
// [text] => ciao
//)
}
......@@ -17,6 +17,7 @@ class Request
{
private static $telegram;
private static $input;
private static $server_response;
private static $methods = array(
'getMe',
......@@ -36,7 +37,11 @@ class Request
public static function initialize(Telegram $telegram)
{
self::$telegram = $telegram;
if (is_object($telegram)) {
self::$telegram = $telegram;
} else {
throw new TelegramException('Telegram pointer is empty!');
}
}
public static function getInput()
......@@ -50,6 +55,18 @@ class Request
return self::$input;
}
public static function getUpdates($data)
{
if ($update = self::$telegram->getCustomUpdate()) {
self::$input = $update;
} else {
self::$input = self::send('getUpdates', $data);
}
self::log(); //TODO
return self::$input;
}
private static function log()
{
if (!self::$telegram->getLogRequests()) {
......@@ -65,6 +82,33 @@ class Request
return $status;
}
public static function generateGeneralFakeServerSesponse($data = null)
{
//PARAM BINDED IN PHPUNIT TEST FOR TestServerResponse.php
//Maybe this is not the best possible implementation
//No value set in $data ie testing setWekhook
//Provided $data['chat_id'] ie testing sendMessage
$fake_response['ok'] = true; // :)
if (!isset($data)) {
$fake_response['result'] = true;
}
//some data to let iniatilize the class method SendMessage
if (isset($data['chat_id'])) {
$data['message_id'] = '1234';
$data['date'] = '1441378360';
$data['from'] = array( 'id' => 123456789 ,'first_name' => 'botname', 'username'=> 'namebot');
$data['chat'] = array('id'=> $data['chat_id'] );
$fake_response['result'] = $data;
}
return $fake_response;
}
public static function send($action, array $data = null)
{
......@@ -73,17 +117,7 @@ class Request
}
if (defined('PHPUNIT_TESTSUITE')) {
$fake_response['ok'] = 1; // :)
//some fake data just to let iniatilize the class method SendMessage
if (isset($data['chat_id'])) {
$data['message_id'] = '123';
$data['date'] = '123';
$data['chat'] = array('id'=> $data['chat_id'] );
$data['from'] = array( 'id' => 123,'first_name' => 'botname', 'username'=> 'namebot');
$fake_response['result'] = $data;
}
$fake_response = self::generateGeneralFakeServerSesponse($data);
return new ServerResponse($fake_response, self::$telegram->getBotName());
}
......@@ -109,10 +143,13 @@ class Request
$response['ok'] = 1;
$response['error_code'] = 1;
$response['description'] = 'Empty server response';
$result =json_encode($response);
}
//return json_decode($result, true);
return new ServerResponse(json_decode($result, true), self::$telegram->getBotName());
//return $result;
$bot_name = self::$telegram->getBotName();
return new ServerResponse(json_decode($result, true), $bot_name);
}
public static function sendMessage(array $data)
......
This diff is collapsed.
<?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.
* Written by Marco Boretto
*/
namespace Tests\Unit;
use \Longman\TelegramBot\Entities\ServerResponse;
use \Longman\TelegramBot\Entities\Message;
use \Longman\TelegramBot\Request;
/**
* @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 ServerResponseTest extends TestCase
{
/**
* @var \Longman\TelegramBot\Telegram
*/
private $server;
/**
* setUp
*/
protected function setUp()
{
}
/**
* @test
*/
public function sendMessageOk()
{
return '{
"ok":true,
"result":{
"message_id":1234,
"from":{"id":123456789,"first_name":"botname","username":"namebot"},
"chat":{"id":123456789,"first_name":"john","username":"Mjohn"},
"date":1441378360,
"text":"hello"
}
}';
}
public function testSendMessageOk() {
$result = $this->sendMessageOk();
$this->server = new ServerResponse(json_decode($result, true), 'testbot');
$this->assertTrue($this->server->isOk());
$this->assertInstanceOf('\Longman\TelegramBot\Entities\Message', $this->server->getResult());
$this->assertNull($this->server->getErrorCode());
$this->assertNull($this->server->getDescription());
//Message
$this->assertEquals('1234', $this->server->getResult()->getMessageId());
$this->assertEquals('123456789', $this->server->getResult()->getFrom()->getId());
$this->assertEquals('botname', $this->server->getResult()->getFrom()->getFirstName());
$this->assertEquals('namebot', $this->server->getResult()->getFrom()->getUserName());
$this->assertEquals('123456789', $this->server->getResult()->getChat()->getId());
$this->assertEquals('john', $this->server->getResult()->getChat()->getFirstName());
$this->assertEquals('Mjohn', $this->server->getResult()->getChat()->getUserName());
$this->assertEquals('1441378360', $this->server->getResult()->getDate());
$this->assertEquals('hello', $this->server->getResult()->getText());
//... they are not finished...
}
/**
* @test
*/
public function sendMessageFail()
{
return '{
"ok":false,
"error_code":400,
"description":"Error: Bad Request: wrong chat id"
}';
}
public function testSendMessageFail() {
$result = $this->sendMessageFail();
$this->server = new ServerResponse(json_decode($result, true), 'testbot');
$this->assertFalse($this->server->isOk());
$this->assertNull($this->server->getResult());
$this->assertEquals('400', $this->server->getErrorCode());
$this->assertEquals('Error: Bad Request: wrong chat id', $this->server->getDescription());
}
/**
* @test
*/
public function setWebHookOk()
{
return '{"ok":true,"result":true,"description":"Webhook was set"}';
}
public function testSetWebhookOk() {
$result = $this->setWebhookOk();
$this->server = new ServerResponse(json_decode($result, true), 'testbot');
$this->assertTrue($this->server->isOk());
$this->assertTrue($this->server->getResult());
$this->assertNull($this->server->getErrorCode());
$this->assertEquals('Webhook was set', $this->server->getDescription());
}
/**
* @test
*/
public function setWebHookFail()
{
return '{
"ok":false,
"error_code":400,
"description":"Error: Bad request: htttps:\/\/domain.host.org\/dir\/hook.php"
}';
}
public function testSetWebhookFail() {
$result = $this->setWebHookFail();
$this->server = new ServerResponse(json_decode($result, true), 'testbot');
$this->assertFalse($this->server->isOk());
$this->assertNull($this->server->getResult());
$this->assertEquals(400, $this->server->getErrorCode());
$this->assertEquals("Error: Bad request: htttps://domain.host.org/dir/hook.php", $this->server->getDescription());
}
/**
* @test
*/
public function getUpdatesArray()
{
return '{
"ok":true,
"result":[
{"update_id":123,
"message":{
"message_id":90,
"from":{"id":123456789,"first_name":"John","username":"Mjohn"},
"chat":{"id":123456789,"first_name":"John","username":"Mjohn"},
"date":1441569067,
"text":"\/start"}
},
{"update_id":124,
"message":{
"message_id":91,
"from":{"id":123456788,"first_name":"Patrizia","username":"Patry"},
"chat":{"id":123456788,"first_name":"Patrizia","username":"Patry"},
"date":1441569073,
"text":"Hello!"}
},
{"update_id":125,
"message":{
"message_id":92,
"from":{"id":123456789,"first_name":"John","username":"MJohn"},
"chat":{"id":123456789,"first_name":"John","username":"MJohn"},
"date":1441569094,
"text":"\/echo hello!"}
},
{"update_id":126,
"message":{
"message_id":93,
"from":{"id":123456788,"first_name":"Patrizia","username":"Patry"},
"chat":{"id":123456788,"first_name":"Patrizia","username":"Patry"},
"date":1441569112,
"text":"\/echo the best"
}
}
]
}';
}
/**
* @test
*/
public function getUpdatesEmpty()
{
return '{"ok":true,"result":[]}';
}
/**
* @test
*/
public function testSetGeneralTestFakeResponse() {
//setWebhook ok
$fake_response = Request::generateGeneralFakeServerSesponse();
$this->server = new ServerResponse($fake_response, 'testbot');
$this->assertTrue($this->server->isOk());
$this->assertTrue($this->server->getResult());
$this->assertNull($this->server->getErrorCode());
$this->assertEquals('', $this->server->getDescription());
//sendMessage ok
$fake_response = Request::generateGeneralFakeServerSesponse(['chat_id' => 123456789, 'text' => 'hello']);
$this->server = new ServerResponse($fake_response, 'testbot');
$this->assertTrue($this->server->isOk());
$this->assertInstanceOf('\Longman\TelegramBot\Entities\Message', $this->server->getResult());
$this->assertNull($this->server->getErrorCode());
$this->assertNull($this->server->getDescription());
//Message
$this->assertEquals('1234', $this->server->getResult()->getMessageId());
$this->assertEquals('1441378360', $this->server->getResult()->getDate());
$this->assertEquals('hello', $this->server->getResult()->getText());
//Message //User
$this->assertEquals('123456789', $this->server->getResult()->getFrom()->getId());
$this->assertEquals('botname', $this->server->getResult()->getFrom()->getFirstName());
$this->assertEquals('namebot', $this->server->getResult()->getFrom()->getUserName());
//Message //Chat
$this->assertEquals('123456789', $this->server->getResult()->getChat()->getId());
$this->assertEquals('', $this->server->getResult()->getChat()->getFirstName());
$this->assertEquals('', $this->server->getResult()->getChat()->getUserName());
//... they are not finished...
}
}
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