Commit 9903d7ac authored by MBoretto's avatar MBoretto

get update works

parent e9f04e40
#!/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();
}
......@@ -27,7 +27,7 @@ class SendtoallCommand extends Command
//need Mysql
protected $need_mysql = true;
public function executeFail()
public function executeNoDB()
{
//Database not setted or without connection
//Preparing message
......
......@@ -50,13 +50,13 @@ abstract class Command
) {
return $this->execute();
}
return $this->executeFail();
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 executeFail()
public function executeNoDB()
{
}
......
......@@ -82,6 +82,43 @@ class DB
}
}
/**
* fetch message from DB
*
* @param fetch Message from the DB
*
* @return bool/ array with data
*/
public static function selectMessages($limit = null)
{
if (!self::isDbConnected()) {
return false;
}
try {
$query = 'SELECT * FROM `'.TB_MESSAGES.'`';
$query .= ' ORDER BY '.TB_MESSAGES.'.`update_id` DESC';
$tokens = [];
if (!is_null($limit)) {
//$query .=' LIMIT :limit ';
//$tokens[':limit'] = $limit;
$query .=' LIMIT '.$limit;
}
//echo $query;
$sth = self::$pdo->prepare($query);
//$sth->execute($tokens);
$sth->execute();
$results = $sth->fetchAll(\PDO::FETCH_ASSOC);
} catch (PDOException $e) {
throw new TelegramException($e->getMessage());
}
return $results;
}
/**
* Convert from unix timestamp to timestamp
......@@ -211,7 +248,7 @@ class DB
*
* @return bool
*/
//TODO separe send from query?
public static function sendToActiveChats(
$callback_function,
array $data,
......
......@@ -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,18 +22,33 @@ 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'] & is_array($data['result'])) {
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;
}
} elseif ($data['ok'] & $data['result'] == true) {
} else {
if ($data['ok'] & $data['result'] == true) {
//Response from setWebhook set
$this->ok = $data['ok'];
$this->result = true;
......@@ -44,13 +59,15 @@ class ServerResponse extends Entity
} 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;
......@@ -77,6 +94,11 @@ class ServerResponse extends Entity
}
}
//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;
......
......@@ -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)
{
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()) {
......@@ -126,12 +143,13 @@ class Request
$response['ok'] = 1;
$response['error_code'] = 1;
$response['description'] = 'Empty server response';
$result =$response;
$result =json_encode($response);
}
//return $result;
return new ServerResponse(json_decode($result, true), self::$telegram->getBotName());
$bot_name = self::$telegram->getBotName();
return new ServerResponse(json_decode($result, true), $bot_name);
}
public static function sendMessage(array $data)
......
......@@ -30,7 +30,7 @@ class Telegram
*
* @var string
*/
protected $version = '0.16.0';
protected $version = '0.17.0';
/**
* Telegram API key
......@@ -152,29 +152,6 @@ class Telegram
$this->mysql_enabled = true;
}
/**
* Set custom update string for debug purposes
*
* @param string $update
*
* @return \Longman\TelegramBot\Telegram
*/
public function setCustomUpdate($update)
{
$this->update = $update;
return $this;
}
/**
* Get custom update string for debug purposes
*
* @return string $update
*/
public function getCustomUpdate()
{
return $this->update;
}
/**
* Get commands list
*
......@@ -271,8 +248,71 @@ class Telegram
return $this->log_path;
}
/**
* Set custom update string for debug purposes
*
* @param string $update
*
* @return \Longman\TelegramBot\Telegram
*/
public function setCustomUpdate($update)
{
$this->update = $update;
return $this;
}
/**
* Get custom update string for debug purposes
*
* @return string $update in json
*/
public function getCustomUpdate()
{
return $this->update;
}
/**
* Handle bot request
* Handle getUpdates method
*
* @return \Longman\TelegramBot\Telegram
*/
public function handleGetUpdates($limit = null, $timeout = null)
{
//DB Query
$last_message = DB::selectMessages(1);
if (isset($last_message[0]['update_id'])) {
//As explained in the telegram bot api documentation
$offset = $last_message[0]['update_id']+1;
} else {
$offset = null;
}
//arrive a server Response object
$ServerResponse = Request::getUpdates([
'offset' => $offset ,
'limit' => $limit,
'timeout' => $timeout
]);
if ($ServerResponse->isOk()) {
$results = '';
$n_update = count($ServerResponse->getResult());
for ($a = 0; $a < $n_update; $a++) {
$result = $this->processUpdate($ServerResponse->getResult()[$a]);
}
print(date('Y-m-d H:i:s', time()).' - Processed '.$a." updates\n");
} else {
print(date('Y-m-d H:i:s', time())." - Fail fetch updates\n");
}
//return $results
}
/**
* Handle bot request from wekhook
*
* @return \Longman\TelegramBot\Telegram
*/
......@@ -289,6 +329,17 @@ class Telegram
}
$update = new Update($post, $this->bot_name);
return $this->processUpdate($update);
}
/**
* Process Handle bot request
*
* @return \Longman\TelegramBot\Telegram
*/
public function processUpdate(update $update)
{
//Load admin Commands
if ($this->admin_enabled) {
......@@ -308,9 +359,8 @@ class Telegram
DB::insertRequest($update);
$message = $update->getMessage();
// check type
$message = $update->getMessage();
$type = $message->getType();
switch ($type) {
......@@ -321,29 +371,40 @@ class Telegram
case 'command':
// execute command
$command = $message->getCommand();
return $this->executeCommand($command, $update);
break;
case 'new_chat_participant':
// trigger new participant
$command = 'Newchatparticipant';
return $this->executeCommand($command, $update);
break;
case 'left_chat_participant':
// trigger left chat participant
$command = 'Leftchatparticipant';
return $this->executeCommand($command, $update);
break;
case 'new_chat_title':
// trigger new_chat_title
$command = 'Newchattitle';
return $this->executeCommand($command, $update);
break;
case 'delete_chat_photo':
// trigger delete_chat_photo
$command = 'Deletechatphoto';
return $this->executeCommand($command, $update);
break;
case 'group_chat_created':
// trigger group_chat_created
$command = 'Groupchatcreated';
return $this->executeCommand($command, $update);
break;
}
return $this->executeCommand($command, $update);
}
/**
......
......@@ -151,6 +151,71 @@ class ServerResponseTest extends TestCase
}
/**
* @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();
......
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