Commit 15aade22 authored by MBoretto's avatar MBoretto

Download file works and fixes

parent 5caebd47
......@@ -22,9 +22,12 @@ API](https://telegram.org/blog/bot-revolution) allowing integrators of
all sorts to bring automated interactions to the mobile platform. This
Bot aims to provide a platform where one could simply write a plugin
and have interactions in a matter of minutes.
- The Bot supports Reply Markup and handle commands in group chat with
multiple bot.
- The Bot can retrive update with webhook and by getUpdate methods.
The Bot can:
- retrive update with webhook and by getUpdate methods.
- supports all types and methods according to Telegram API (2015 October 8).
- handle commads in chat with other bots.
It is ready for the channels support.
## Instructions
......@@ -115,7 +118,7 @@ composer require longman/telegram-bot
### Choose how to retrieve Telegram updates
The bot can handle updates with **webhook** or **getUpdate** method:
| Method | Webhook | getUpdate |
| | Webhook | getUpdate |
| ---- | :----: | :----: |
| Description | Telegram send the update directy to your host | Yuo have to fetch Telegram updates |
| Host with https | Required | Not required |
......@@ -148,7 +151,6 @@ try {
And open your *set.php* via browser.
After, create *hook.php* (or just edit *example-hook.php*) and put:
```php
<?php
......@@ -168,6 +170,13 @@ try {
// echo $e;
}
```
###Self Signed Certificate
To upload the certificate add the certificate path as param in *set.php*:
```php
$result = $telegram->setWebHook($url, $certificate_path);
```
## getUpdate installation
You need the database Mysql active.
......@@ -201,6 +210,18 @@ then run
```
./getUpdateCLI.php
```
### Types
All types implemented according to Telegram API (2015 October 8).
### Methods New!
All methods implemented according to Telegram API (2015 October 8).
TODO example to use methods
```php
$result = Request::sendPhoto($data,'image.jpg');
```
## Utilis
### MySQL storage (Recomended)
If you want insert in database messages/users/chats for further usage
......@@ -218,8 +239,6 @@ You can set a custom prefix to all the tables while you are enabling Mysql:
```php
$telegram->enableMySQL($credentials, $BOT_NAME.'_');
```
### Types New!
All types implemented (except InputFile) according to Telegram API (2015 September 18).
### Commands
The bot is able to recognise commands in chat with multiple bot(/command@mybot ).
......@@ -268,6 +287,11 @@ example, google geocode/timezone api key for date command:
```php
$telegram->setCommandConfig('date',
array('google_api_key'=>'your_google_api_key_here'));
```
### Upload and Download directory
You can overwrite the default Upload and download directory with:
```php
```
### Send message to all active chats
To do this you have to enable the Mysql connection.
......@@ -276,15 +300,12 @@ Here's an example of use:
```php
$results = $telegram->sendToActiveChats(
'sendMessage', //callback function to execute (see Request.php methods)
array('text'=>'Hey! Checkout the new feature!!'), //Param to
evaluate the request
array('text'=>'Hey! Checkout the new feature!!'), //Param to evaluate the request
true, //Send to chats (group chat)
true, //Send to users (single chat)
null, //'yyyy-mm-dd hh:mm:ss' date range from
null //'yyyy-mm-dd hh:mm:ss' date range to
);
print_r($results);
```
### Logging
......
......@@ -26,6 +26,8 @@ try {
//$telegram->setLogRequests(true);
//$telegram->setLogPath($BOT_NAME.'.log');
//$telegram->setLogVerbosity(3);
//$telegram->setDownloadPath("../Download");
//$telegram->setUploadPath("../Upload");
// handle telegram getUpdate request
$telegram->handleGetUpdates();
......
......@@ -23,6 +23,8 @@ try {
//$telegram->setLogPath($BOT_NAME.'.log');
//$telegram->setLogVerbosity(4);
//$telegram->setDownloadPath("../Download");
//$telegram->setUploadPath("../Upload");
// handle telegram webhook request
$telegram->handle();
} catch (Longman\TelegramBot\Exception\TelegramException $e) {
......
......@@ -10,6 +10,8 @@ try {
$telegram = new Longman\TelegramBot\Telegram($API_KEY, $BOT_NAME);
// set webhook
$result = $telegram->setWebHook($link);
//Uncomment to use certificate
//$result = $telegram->setWebHook($link, $path_certificate);
if ($result->isOk()) {
echo $result->getDescription();
}
......
......@@ -66,7 +66,7 @@ class ChatsCommand extends Command
$chat = new Chat($result);
if ($chat->isSingleChat()) {
if ($chat->isPrivateChat()) {
//$text .= '- U '.$chat->getFirstName()."\n";
$text .= '- U '.$this->tryMentionChat($chat)."\n";
......
......@@ -73,7 +73,7 @@ class SendtoallCommand extends Command
$ServerResponse = $result->getResult();
$chat = $ServerResponse->getChat();
if ($chat->isSingleChat()) {
if ($chat->isPrivateChat()) {
$name = $chat->getFirstName();
$type = 'user';
} else {
......
<?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\Commands;
use Longman\TelegramBot\Request;
use Longman\TelegramBot\Command;
use Longman\TelegramBot\Entities\Update;
class StartCommand extends Command
{
protected $name = 'start';
protected $description = 'Start command';
protected $usage = '/';
protected $version = '1.0.0';
protected $enabled = true;
protected $public = false;
public function execute()
{
$update = $this->getUpdate();
$message = $this->getMessage();
$chat_id = $message->getChat()->getId();
$data = array();
$data['chat_id'] = $chat_id;
$text = "Hi there!\nType /help to see all commands!";
$data['text'] = $text;
$result = Request::sendMessage($data);
return $result;
}
}
......@@ -16,6 +16,7 @@ namespace Longman\TelegramBot\Commands;
use Longman\TelegramBot\Request;
use Longman\TelegramBot\Command;
use Longman\TelegramBot\Entities\Update;
use Longman\TelegramBot\Entities\File;
class WhoamiCommand extends Command
{
......@@ -44,7 +45,7 @@ class WhoamiCommand extends Command
. ' ' . $message->getFrom()->getLastName();
$caption .= "\n" . 'Username: ' . $message->getFrom()->getUsername();
//Fetch user profile photo
$limit = 10;
$offset = null;
$ServerResponse = Request::getUserProfilePhotos([
......@@ -54,22 +55,13 @@ class WhoamiCommand extends Command
]);
//Check if the request isOK
if($ServerResponse->isOk()){
if ($ServerResponse->isOk()) {
$UserProfilePhoto = $ServerResponse->getResult();
$totalcount = $UserProfilePhoto->getTotalCount();
} else {
$totalcount = 0;
}
//$photos = $UserProfilePhoto->getPhotos();
////I pick the latest photo with the hight definition
//$photo = $photos[0][2];
//$file_id = $photo->getFileId();
//$ServerResponse = Request::getFile(['file_id' => $file_id]);
$data = [];
$data['chat_id'] = $chat_id;
$data['reply_to_message_id'] = $message_id;
......@@ -80,13 +72,22 @@ class WhoamiCommand extends Command
$photo = $photos[0][2];
$file_id = $photo->getFileId();
$data['photo'] = $file_id;
$data['caption'] = $caption;
$result = Request::sendPhoto($data);
} else {
//Download the image pictures
//Download after send message response to speedup response
$file_id = $photo->getFileId();
$ServerResponse = Request::getFile(['file_id' => $file_id]);
if ($ServerResponse->isOk()) {
Request::downloadFile($ServerResponse->getResult());
}
} else {
//No Photo just send text
$data['text'] = $caption;
$result = Request::sendMessage($data);
}
......
......@@ -276,13 +276,15 @@ class DB
try {
//chats table
$sth2 = self::$pdo->prepare('INSERT INTO `'.TB_CHATS.'`
(`id`, `title`, `created_at` ,`updated_at`)
VALUES (:id, :title, :date, :date)
(`id`, `type`, `title`, `created_at` ,`updated_at`)
VALUES (:id, :type, :title, :date, :date)
ON DUPLICATE KEY UPDATE `title`=:title, `updated_at`=:date');
$chat_title = $chat->getTitle();
$type = $chat->getType();
$sth2->bindParam(':id', $chat_id, \PDO::PARAM_INT);
$sth2->bindParam(':type', $type, \PDO::PARAM_INT);
$sth2->bindParam(':title', $chat_title, \PDO::PARAM_STR, 255);
$sth2->bindParam(':date', $date, \PDO::PARAM_STR);
......
......@@ -37,23 +37,34 @@ class Chat extends Entity
$this->last_name = isset($data['last_name']) ? $data['last_name'] : null;
$this->username = isset($data['username']) ? $data['username'] : null;
}
public function isGroupChat()
{
if ($this->id < 0) {
if ($this->type == 'group' || $this->id < 0 ) {
return true;
} else {
return false;
}
}
public function isSingleChat()
public function isPrivateChat()
{
if ($this->id > 0) {
if ($this->type == 'private' || $this->id > 0) {
return true;
} else {
return false;
}
}
public function isChannel()
{
if ($this->type == 'channel') {
return true;
} else {
return false;
}
}
public function getId()
{
......
......@@ -12,6 +12,7 @@ namespace Longman\TelegramBot;
use Longman\TelegramBot\Exception\TelegramException;
use Longman\TelegramBot\Entities\ServerResponse;
use Longman\TelegramBot\Entities\File;
class Request
{
......@@ -167,6 +168,58 @@ class Request
return $result;
}
public static function downloadFile(File $file)
{
$path = $file->getFilePath();
#Create the directory
$basepath = self::$telegram->getDownloadPath();
$loc_path = $basepath.'/'.$path;
$dirname = dirname($loc_path);
if (!is_dir($dirname)) {
if(!mkdir($dirname, 0755, true)) {
throw new TelegramException('Directory '.$dirname.' cant be created');
}
}
# open file to write
$fp = fopen ($loc_path, 'w+');
if ($fp === false) {
throw new TelegramException('File cant be created');
}
$ch = curl_init();
if ($ch === false) {
throw new TelegramException('Curl failed to initialize');
}
$curlConfig = array(
CURLOPT_URL => 'https://api.telegram.org/file/bot' . self::$telegram->getApiKey() . '/' . $path,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HEADER => 0,
CURLOPT_BINARYTRANSFER => true,
CURLOPT_CONNECTTIMEOUT => 10,
CURLOPT_FILE => $fp
);
curl_setopt_array($ch, $curlConfig);
$result = curl_exec($ch);
if ($result === false) {
throw new TelegramException(curl_error($ch), curl_errno($ch));
}
# close curl
curl_close($ch);
# close local file
fclose($fp);
if (filesize($loc_path) > 0) {
return true;
} else {
return false;
}
}
protected static function encodeFile($file)
{
return new \CURLFile($file);
......@@ -185,7 +238,7 @@ class Request
$result = self::executeCurl($action, $data);
echo $result;
//echo $result;
print_r(json_decode($result, true));
$bot_name = self::$telegram->getBotName();
......
......@@ -170,6 +170,9 @@ class Telegram
$this->api_key = $api_key;
$this->bot_name = $bot_name;
//Set default download and upload dir
$this->setDownloadPath(BASE_PATH . "/../Download");
$this->setUploadPath(BASE_PATH . "/../Upload");
Request::initialize($this);
}
......@@ -368,7 +371,7 @@ class Telegram
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");
echo $ServerResponse->printError();
echo $ServerResponse->printError()."\n";
}
//return $results
......@@ -594,9 +597,11 @@ class Telegram
*/
public function setUploadPath($folder)
{
if (!is_dir($folder)) {
throw new TelegramException('Upload folder not exists!');
}
//if (!is_dir($folder)) {
// if(!mkdir($folder, 0755, true)) {
// throw new TelegramException('Directory '.$folder.' cant be created');
// }
//}
$this->upload_path = $folder;
return $this;
}
......@@ -606,7 +611,7 @@ class Telegram
*
* @return string
*/
public function getUploadPath($folder)
public function getUploadPath()
{
return $this->upload_path;
}
......@@ -618,10 +623,12 @@ class Telegram
*/
public function setDownloadPath($folder)
{
if (!is_dir($folder)) {
throw new TelegramException('Download folder not exists!');
}
$this->upload_path = $folder;
//if (!is_dir($folder)) {
// if(!mkdir($folder, 0755, true)) {
// throw new TelegramException('Directory '.$folder.' cant be created');
// }
//}
$this->download_path = $folder;
return $this;
}
......@@ -630,7 +637,7 @@ class Telegram
*
* @return string
*/
public function getDownloadPath($folder)
public function getDownloadPath()
{
return $this->download_path;
}
......@@ -692,12 +699,13 @@ class Telegram
*
* @return string
*/
public function setWebHook($url)
public function setWebHook($url, $path_certificate = null)
{
if (empty($url)) {
throw new TelegramException('Hook url is empty!');
}
$result = Request::setWebhook($url);
$result = Request::setWebhook($url, $path_certificate);
if (!$result->isOk()) {
throw new TelegramException(
......
......@@ -41,6 +41,7 @@ CREATE TABLE `users` (
CREATE TABLE `chats` (
`id` bigint NOT NULL DEFAULT '0' COMMENT 'Unique user or chat identifier',
`type` CHAR(10) DEFAULT '' COMMENT 'chat type private groupe or channel',
`title` CHAR(255) DEFAULT '' COMMENT 'chat title null if case of single chat with the bot',
`created_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00' COMMENT 'Entry date creation',
`updated_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00' COMMENT 'Entry date update',
......
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