From 80feafc0634223bc1e650bb9669c4570b2bbdde5 Mon Sep 17 00:00:00 2001 From: Finalgalaxy Date: Sat, 24 Feb 2018 21:34:41 +0100 Subject: [PATCH] Reorganized code in comments. --- README.md | 10 +++++----- get_updates.php | 24 +++++++++++++++--------- include/functions.php | 4 ++-- install.php | 16 +++++++++++++--- send_message.php | 15 ++++++++------- send_photo.php | 11 +++++++---- 6 files changed, 50 insertions(+), 30 deletions(-) diff --git a/README.md b/README.md index 85d7139..59b3775 100644 --- a/README.md +++ b/README.md @@ -8,8 +8,8 @@ Useful if you want to **manage** a Telegram bot from a web server AND secure you Easy to use, to configure and lightweight. ## Requirements -1. Any web hosting service with PHP+SQL plan (Even free tier options, for example https://www.000webhost.com/ or https://it.altervista.org/ etc.); -2. The API key of your Telegram bot (Read Step 1 to discover how to create a bot: https://github.com/fabnicolas/telegram-bot-readytouse/blob/master/README.md) +1. **Any** web hosting service with **PHP+SQL plan** (Even free tier options, for example https://www.000webhost.com/ or https://it.altervista.org/ etc.); +2. The **API key of your Telegram bot** (Read Step 1 to discover how to create a bot: https://github.com/fabnicolas/telegram-bot-readytouse/blob/master/README.md) ## Setup (Web Server) @@ -20,7 +20,7 @@ return [ 'telegram_bot_API_key' => "your_key", 'db_host' => "localhost", 'db_user' => "your_username", - "db_password" => "your_password", + 'db_password' => "your_password", 'db_name' => "your_database" ]; ?> @@ -94,8 +94,8 @@ This is a wrapped and modified version of getUpdates Telegram API: https://core. The wrapped version: - **Simplifies** the original API by cutting unnecessary data for a client-to-bot successful communication, showing only `status` of the request, a `message` list and `next_update_id`; -- Caches info provided by the original API in a RDBMS. It's eventually possible to separate the caching process from the read requests themselves; -- Provides you the last `next_update_id` in a dedicated JSON attribute so that your application can make new requests without recalcolating the new `update_id` parameter. +- **Caches** info provided by the original API in a RDBMS. It's eventually possible to separate the caching process from the read requests themselves; +- **Provides** you the last `next_update_id` in a dedicated JSON attribute so that your application can make new requests without recalcolating the new `update_id` parameter. **Notice**: `update_id` in the request payload should be implemented as follow: - = `0` at start of your application; diff --git a/get_updates.php b/get_updates.php index 986a957..b3f04bd 100644 --- a/get_updates.php +++ b/get_updates.php @@ -5,30 +5,36 @@ $success=false; +// Let's include database and initialize our telegram bot. $db = include_once(__DIR__."/include/use_db.php"); - $telegram_bot = new TelegramBot($config['telegram_bot_API_key']); -$update_id = post_parameter('update_id'); -$update_id = $update_id!=null ? $update_id : 0; -// We fetch and parse updates from Telegram API to store. +// Parameter 'update_id'; 0 if null. +$update_id = post_parameter('update_id', 0); + +// We fetch and parse updates from Telegram API to store inside database. $result = $telegram_bot->getParsedUpdates(null,$update_id); if($result){ foreach($result as $key=>$message_params){ - // Insert all the updates (messages) inside the DB table for further reuses. + // Insert all the updates (messages) inside the DB table for further reuses (row by row). $statement = $db->getPDO()->prepare( "INSERT INTO updates (update_id, message_id, from_id, from_username, date, text) VALUES (:update_id, :message_id, :from_id, :from_username, :date, :text)"); $statement->execute($message_params); } } +// Note: you can separate this script in a separate file as 'caching script' for a cron job. -$telegram_id = post_parameter('chat_id'); + +$telegram_id = post_parameter('chat_id'); // chat_id of the target we want to analyze data from. if(!empty($telegram_id) && is_numeric($telegram_id)){ + // Let's retrieve from RDBMS all new incoming messages. $statement = $db->getPDO()->prepare("SELECT update_id,text FROM updates WHERE update_id >= :update_id AND from_id = :from_id ORDER BY update_id ASC"); $statement->execute(array('update_id'=>$update_id, 'from_id'=>$telegram_id)); $result = $statement->fetchAll(); + + // Let's parse those data and get IDs of the messages to mark as read (By deleting their records from database). $parsed_result = array(); $update_ids_todelete = array(); foreach($result as $message){ @@ -38,16 +44,16 @@ } $next_update_id=$update_id; if(!empty($update_ids_todelete)){ + // Deleting procedure. $update_ids_string=$db->in_composer($update_ids_todelete); $statement = $db->getPDO()->prepare("DELETE FROM `updates` WHERE FIND_IN_SET(update_id, :update_id)"); $statement->execute(array('update_id'=>$update_ids_string)); $next_update_id=$update_ids_todelete[count($update_ids_todelete)-1]+1; } - echo json(array('status'=>0, 'message'=>$parsed_result, 'next_update_id'=>$next_update_id)); $success=true; } -if(!$success) http_response_code(400); -else http_response_code(200); +if(!$success) {echo json(array('status'=>1, 'message'=>'Error on backend.')); http_response_code(200);} +else {echo json(array('status'=>0, 'message'=>$parsed_result, 'next_update_id'=>$next_update_id)); http_response_code(400);} ?> diff --git a/include/functions.php b/include/functions.php index aa338ab..8bfcecf 100644 --- a/include/functions.php +++ b/include/functions.php @@ -5,8 +5,8 @@ function enable_errors(){ error_reporting(E_ALL); } -function post_parameter($key){ - return isset($_POST[$key]) ? $_POST[$key] : null; +function post_parameter($key,$default=null){ + return isset($_POST[$key]) ? $_POST[$key] : $default; } function execute_atomically($function_to_execute){ diff --git a/install.php b/install.php index f3361ca..2f09c8c 100644 --- a/install.php +++ b/install.php @@ -1,7 +1,16 @@ pdo->query("CREATE TABLE IF NOT EXISTS `updates` ( +$db->pdo->query( + "CREATE TABLE IF NOT EXISTS `updates` ( `update_id` bigint(20) NOT NULL, `message_id` bigint(20) NOT NULL, `from_id` bigint(20) NOT NULL, @@ -9,7 +18,8 @@ `date` bigint(20) NOT NULL, `text` text NOT NULL, PRIMARY KEY (`update_id`,`message_id`) - )"); + )"); -unlink(__FILE__); +class SelfDestroy{function __destruct(){unlink(__FILE__);}} +$installation_finished = new DeleteOnExit(); ?> \ No newline at end of file diff --git a/send_message.php b/send_message.php index 69e78fc..c3b06c1 100644 --- a/send_message.php +++ b/send_message.php @@ -5,16 +5,17 @@ $success=false; -$telegram_id = post_parameter('chat_id'); +$telegram_id = post_parameter('chat_id'); // chat_id of the target user to send message to. if(!empty($telegram_id) && is_numeric($telegram_id)){ - $message = post_parameter('message'); + $message = post_parameter('message'); // text to send to the target user. if(!empty($message)){ - $gigi = new TelegramBot($config['telegram_bot_API_key']); - $gigi->sendMessage($message, $telegram_id); - $success=true; + // Let's use telegram bot to send message to the target user. + $telegram_bot = new TelegramBot($config['telegram_bot_API_key']); + $telegram_bot->sendMessage($message, $telegram_id); + $success=true; // The operation was successful. } } -if(!$success) {echo json(array('status'=>0, message=>'Message sent.')); http_response_code(400);} -else {echo json(array('status'=>1, message=>'Error on backend.')); http_response_code(200);} +if(!$success) {echo json(array('status'=>1, message=>'Error on backend.')); http_response_code(200);} +else {echo json(array('status'=>0, message=>'Message sent.')); http_response_code(400);} ?> diff --git a/send_photo.php b/send_photo.php index ab51b4b..c96ac14 100644 --- a/send_photo.php +++ b/send_photo.php @@ -6,16 +6,19 @@ $success=false; -$telegram_id = post_parameter('chat_id'); +$telegram_id = post_parameter('chat_id'); // chat_id of the target user to send photo to. if(!empty($telegram_id) && is_numeric($telegram_id)){ + // Let's instantiate an uploader to upload our image, sent in payload, stored in $_FILES['image']. $uploader = new Uploader("./tmp/"); if(!empty($_FILES['image'])){ if(($file=($uploader->uploadImage($_FILES['image'])))!=false){ - $gigi = new TelegramBot($config['telegram_bot_API_key']); - $gigi->sendPhoto(($uploader->getDirectory()).$file, $telegram_id, function() use ($uploader, $file){ + // If the image was uploaded successfully to our server, let's send it to the target. + $telegram_bot = new TelegramBot($config['telegram_bot_API_key']); + $telegram_bot->sendPhoto(($uploader->getDirectory()).$file, $telegram_id, function() use ($uploader, $file){ + // When communication is finished, remove the image from the server. $uploader->destroyImage($file); }); - $success=true; + $success=true; // The operation was successful. } } }