Skip to content

Commit

Permalink
Reorganized code in comments.
Browse files Browse the repository at this point in the history
  • Loading branch information
fabnicolas committed Feb 24, 2018
1 parent f80cf99 commit 80feafc
Show file tree
Hide file tree
Showing 6 changed files with 50 additions and 30 deletions.
10 changes: 5 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Expand All @@ -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"
];
?>
Expand Down Expand Up @@ -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;
Expand Down
24 changes: 15 additions & 9 deletions get_updates.php
Original file line number Diff line number Diff line change
Expand Up @@ -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){
Expand All @@ -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);}
?>
4 changes: 2 additions & 2 deletions include/functions.php
Original file line number Diff line number Diff line change
Expand Up @@ -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){
Expand Down
16 changes: 13 additions & 3 deletions install.php
Original file line number Diff line number Diff line change
@@ -1,15 +1,25 @@
<?php
/*
THIS SCRIPT WILL SELF-DESTRUCT AFTER EXECUTION!
The purpose of this script is clear: create table `updates` inside your RDBMS.
Everyone loves auto-installers, right?
(Make sure your DB data are VALID before executing this script.)
*/
$db = include_once(__DIR__."/include/use_db.php");

$db->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,
`from_username` varchar(255) NOT NULL,
`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();
?>
15 changes: 8 additions & 7 deletions send_message.php
Original file line number Diff line number Diff line change
Expand Up @@ -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);}
?>
11 changes: 7 additions & 4 deletions send_photo.php
Original file line number Diff line number Diff line change
Expand Up @@ -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.
}
}
}
Expand Down

0 comments on commit 80feafc

Please sign in to comment.