Commit f1d366b7 authored by LONGMAN's avatar LONGMAN

Added database support

parent 60a5311e
...@@ -59,7 +59,7 @@ Instructions ...@@ -59,7 +59,7 @@ Instructions
## Installation ## Installation
You need server with https and composer support. You need server with https and composer support.
Create composer.json filde: Create composer.json file:
```js ```js
{ {
"name": "yourproject/yourproject", "name": "yourproject/yourproject",
...@@ -97,7 +97,7 @@ $telegram->setWebHook('https://yourdomain/yourpath_to_hook.php'); ...@@ -97,7 +97,7 @@ $telegram->setWebHook('https://yourdomain/yourpath_to_hook.php');
``` ```
After c reate hook.php and put: After create hook.php and put:
```php ```php
<?php <?php
...@@ -113,6 +113,16 @@ $telegram->handle(); ...@@ -113,6 +113,16 @@ $telegram->handle();
``` ```
If you want insert in database messages for further usage in commands, create database and import structure.sql and enable mysql support after object creation and BEFORE handle method
```php
<?php
$credentials = array('host'=>'localhost', 'user'=>'dbuser', 'password'=>'dbpass', 'database'=>'dbname');
$telegram->enableMySQL($credentials);
```
This code is available on [Github][0]. Pull requests are welcome. This code is available on [Github][0]. Pull requests are welcome.
......
...@@ -18,7 +18,8 @@ ...@@ -18,7 +18,8 @@
} }
], ],
"require": { "require": {
"php": ">=5.3.0" "php": ">=5.3.0",
"ext-pdo": "*"
}, },
"autoload": { "autoload": {
"psr-4": { "psr-4": {
......
...@@ -10,7 +10,7 @@ ...@@ -10,7 +10,7 @@
namespace Longman\TelegramBot\Entities; namespace Longman\TelegramBot\Entities;
class Chat class Chat extends Entity
{ {
protected $id; protected $id;
...@@ -26,6 +26,11 @@ class Chat ...@@ -26,6 +26,11 @@ class Chat
throw new \Exception('id is empty!'); throw new \Exception('id is empty!');
} }
$this->title = isset($data['title']) ? $data['title'] : null;
$this->first_name = isset($data['first_name']) ? $data['first_name'] : null;
$this->last_name = isset($data['last_name']) ? $data['last_name'] : null;
$this->username = isset($data['username']) ? $data['username'] : null;
} }
......
<?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\Entities;
class Entity
{
public function toJSON() {
$reflection = new \ReflectionObject($this);
$properties = $reflection->getProperties();
$fields = array();
foreach($properties as $property) {
$name = $property->getName();
$property->setAccessible(true);
$value = $property->getValue($this);
$fields[$name] = $value;
}
$json = json_encode($fields);
return $json;
}
}
...@@ -12,7 +12,7 @@ namespace Longman\TelegramBot\Entities; ...@@ -12,7 +12,7 @@ namespace Longman\TelegramBot\Entities;
class Message class Message extends Entity
{ {
protected $message_id; protected $message_id;
...@@ -88,6 +88,19 @@ class Message ...@@ -88,6 +88,19 @@ class Message
$this->text = isset($data['text']) ? $data['text'] : null; $this->text = isset($data['text']) ? $data['text'] : null;
$this->forward_from = isset($data['forward_from']) ? $data['forward_from'] : null;
if (!empty($this->forward_from)) {
$this->forward_from = new User($this->forward_from);
}
$this->forward_date = isset($data['forward_date']) ? $data['forward_date'] : null;
$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 Message($this->reply_to_message);
}
} }
...@@ -131,6 +144,21 @@ class Message ...@@ -131,6 +144,21 @@ class Message
return $this->chat; return $this->chat;
} }
public function getForwardFrom() {
return $this->forward_from;
}
public function getForwardDate() {
return $this->forward_date;
}
public function getReplyToMessage() {
return $this->reply_to_message;
}
public function getText($without_cmd = false) { public function getText($without_cmd = false) {
$text = $this->text; $text = $this->text;
if ($without_cmd) { if ($without_cmd) {
......
...@@ -12,7 +12,7 @@ namespace Longman\TelegramBot\Entities; ...@@ -12,7 +12,7 @@ namespace Longman\TelegramBot\Entities;
class Update class Update extends Entity
{ {
protected $update_id; protected $update_id;
......
...@@ -10,7 +10,7 @@ ...@@ -10,7 +10,7 @@
namespace Longman\TelegramBot\Entities; namespace Longman\TelegramBot\Entities;
class User class User extends Entity
{ {
protected $id; protected $id;
......
...@@ -70,14 +70,11 @@ class Request ...@@ -70,14 +70,11 @@ class Request
$curlConfig = array( $curlConfig = array(
CURLOPT_URL => 'https://api.telegram.org/bot'.self::$telegram->getApiKey().'/'.$action, CURLOPT_URL => 'https://api.telegram.org/bot'.self::$telegram->getApiKey().'/'.$action,
CURLOPT_POST => true, CURLOPT_POST => true,
CURLOPT_RETURNTRANSFER => true, CURLOPT_RETURNTRANSFER => true
//CURLOPT_HTTPHEADER => array('Content-Type: application/x-www-form-urlencoded'),
//CURLOPT_HTTPHEADER => array('Content-Type: text/plain'),
//CURLOPT_POSTFIELDS => $data
); );
if (!empty($data)) { if (!empty($data)) {
if (substr($data['text'], 0, 1) === '@') { if (!empty($data['text']) && substr($data['text'], 0, 1) === '@') {
$data['text'] = ' '.$data['text']; $data['text'] = ' '.$data['text'];
} }
......
...@@ -72,6 +72,29 @@ class Telegram ...@@ -72,6 +72,29 @@ class Telegram
*/ */
protected $log_path; protected $log_path;
/**
* MySQL Integration
*
* @var boolean
*/
protected $mysql_enabled;
/**
* MySQL credentials
*
* @var array
*/
protected $mysql_credentials = array();
/**
* PDO object
*
* @var \PDO
*/
protected $pdo;
/** /**
* Constructor * Constructor
...@@ -175,11 +198,16 @@ class Telegram ...@@ -175,11 +198,16 @@ class Telegram
$update = new Update($post); $update = new Update($post);
$this->insertRequest($update);
$command = $update->getMessage()->getCommand(); $command = $update->getMessage()->getCommand();
if (!empty($command)) { if (!empty($command)) {
return $this->executeCommand($command, $update); return $this->executeCommand($command, $update);
} }
} }
/** /**
...@@ -223,6 +251,77 @@ class Telegram ...@@ -223,6 +251,77 @@ class Telegram
return false; return false;
} }
/**
* Insert request in db
*
* @return bool
*/
protected function insertRequest(Update $update) {
if (empty($this->pdo)) {
return false;
}
try {
$sth = $this->pdo->prepare('INSERT INTO `messages`
(
`update_id`, `message_id`, `from`, `date`, `chat`, `forward_from`,
`forward_date`, `reply_to_message`, `text`
)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)');
$message = $update->getMessage();
$update_id = $update->getUpdateId();
$message_id = $message->getMessageId();
$from = $message->getFrom()->toJSON();
$date = $message->getDate();
$chat = $message->getChat()->toJSON();
$forward_from = $message->getForwardFrom();
$forward_date = $message->getForwardDate();
$reply_to_message = $message->getReplyToMessage();
if (is_object($reply_to_message)) {
$reply_to_message = $reply_to_message->toJSON();
}
$text = $message->getText();
$sth->bindParam(1, $update_id, \PDO::PARAM_INT);
$sth->bindParam(2, $message_id, \PDO::PARAM_INT);
$sth->bindParam(3, $from, \PDO::PARAM_STR, 255);
$sth->bindParam(4, $date, \PDO::PARAM_INT);
$sth->bindParam(5, $chat, \PDO::PARAM_STR);
$sth->bindParam(6, $forward_from, \PDO::PARAM_STR);
$sth->bindParam(7, $forward_date, \PDO::PARAM_INT);
$sth->bindParam(8, $reply_to_message, \PDO::PARAM_STR);
$sth->bindParam(9, $text, \PDO::PARAM_STR);
$status = $sth->execute();
/*$status = $executeQuery->execute(
array(
$update_id, $message_id, $from, $date, $chat, $forward_from,
$forward_date, $reply_to_message, $text,
)
);*/
}
catch(PDOException $e) {
throw new \Exception($e->getMessage());
}
return true;
}
/** /**
* Add custom commands path * Add custom commands path
* *
...@@ -244,6 +343,47 @@ class Telegram ...@@ -244,6 +343,47 @@ class Telegram
return $this->api_key; return $this->api_key;
} }
/**
* Set Webhook for bot
*
* @return string
*/
public function setWebHook($url){
return Request::send('setWebhook', array('url'=>$url));
}
/**
* Enable MySQL integration
*
* @param array $credentials MySQL credentials
*
* @return string
*/
public function enableMySQL(array $credentials){
if (empty($credentials)) {
throw new \Exception('MySQL credentials not provided!');
}
$this->mysql_credentials = $credentials;
$dsn = 'mysql:host='.$credentials['host'].';dbname='.$credentials['database'];
$options = array(
\PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8',
);
try {
$pdo = new \PDO($dsn, $credentials['user'], $credentials['password'], $options);
$pdo->setAttribute (\PDO::ATTR_ERRMODE, \PDO::ERRMODE_WARNING);
}
catch (\PDOException $e) {
throw new \Exception($e->getMessage());
}
$this->pdo = $pdo;
$this->mysql_enabled = true;
return $this;
}
} }
CREATE TABLE `messages` (
`update_id` bigint UNSIGNED COMMENT 'The update\'s unique identifier.',
`message_id` bigint COMMENT 'Unique message identifier',
`from` CHAR(255) COMMENT 'User object',
`date` int(11) UNSIGNED COMMENT 'Date the message was sent in Unix time',
`chat` CHAR(255) COMMENT 'User or GroupChat object. Conversation the message belongs to — user in case of a private message, GroupChat in case of a group',
`forward_from` CHAR(255) DEFAULT '' COMMENT 'User object. For forwarded messages, sender of the original message',
`forward_date` int(11) UNSIGNED DEFAULT 0 COMMENT 'For forwarded messages, date the original message was sent in Unix time',
`reply_to_message` LONGTEXT COMMENT 'Message object. For replies, the original message. Note that the Message object in this field will not contain further reply_to_message fields even if it itself is a reply.',
`text` LONGTEXT COMMENT 'For text messages, the actual UTF-8 text of the message',
`audio` CHAR(255) DEFAULT '' COMMENT 'Audio object. Message is an audio file, information about the file',
`document` CHAR(255) DEFAULT '' COMMENT 'Document object. Message is a general file, information about the file',
`photo` CHAR(255) DEFAULT '' COMMENT 'Array of PhotoSize objects. Message is a photo, available sizes of the photo',
`sticker` CHAR(255) DEFAULT '' COMMENT 'Sticker object. Message is a sticker, information about the sticker',
`video` CHAR(255) DEFAULT '' COMMENT 'Video object. Message is a video, information about the video',
`contact` CHAR(255) DEFAULT '' COMMENT 'Contact object. Message is a shared contact, information about the contact',
`location` CHAR(255) DEFAULT '' COMMENT 'Location object. Message is a shared location, information about the location',
`new_chat_participant` CHAR(255) COMMENT 'User object. A new member was added to the group, information about them (this member may be bot itself)',
`left_chat_participant` CHAR(255) COMMENT 'User object. A member was removed from the group, information about them (this member may be bot itself)',
`new_chat_title` CHAR(255) DEFAULT '' COMMENT 'A group title was changed to this value',
`new_chat_photo` CHAR(255) DEFAULT '' COMMENT 'Array of PhotoSize objects. A group photo was change to this value',
`delete_chat_photo` tinyint(1) DEFAULT 0 COMMENT 'Informs that the group photo was deleted',
`group_chat_created` tinyint(1) DEFAULT 0 COMMENT 'Informs that the group has been created',
PRIMARY KEY (`update_id`),
KEY `message_id` (`message_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci
\ No newline at end of file
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