Completed
Pull Request — master (#7)
by
unknown
01:37
created
src/Smoqadam/InlineQuery/Result/Article.php 1 patch
Indentation   +7 added lines, -7 removed lines patch added patch discarded remove patch
@@ -5,15 +5,15 @@
 block discarded – undo
5 5
 class Article {
6 6
 
7 7
   public
8
-    $type = 'article',
9
-    $id,
10
-    $title,
11
-    $input_message_content;
8
+	$type = 'article',
9
+	$id,
10
+	$title,
11
+	$input_message_content;
12 12
 
13 13
   public function __construct($title, $content) {
14
-    $this->title = $title;
15
-    $this->input_message_content = $content;
16
-    $this->id = '' . rand();
14
+	$this->title = $title;
15
+	$this->input_message_content = $content;
16
+	$this->id = '' . rand();
17 17
   }
18 18
 
19 19
 }
Please login to merge, or discard this patch.
src/Smoqadam/Keyboard/Inline.php 1 patch
Indentation   +33 added lines, -33 removed lines patch added patch discarded remove patch
@@ -5,51 +5,51 @@
 block discarded – undo
5 5
 class Inline {
6 6
 
7 7
   public
8
-    $inline_keyboard = [];
8
+	$inline_keyboard = [];
9 9
     
10 10
   private
11
-    $current_row = 0;
11
+	$current_row = 0;
12 12
   
13 13
   /**
14
-  * Create new row.
15
-  *
16
-  * @return object
17
-  */
14
+   * Create new row.
15
+   *
16
+   * @return object
17
+   */
18 18
   public function addRow(){
19
-    $this->current_row++;
19
+	$this->current_row++;
20 20
     
21
-    return $this;
21
+	return $this;
22 22
   }
23 23
   
24 24
   /**
25
-  * Add new button to current row.
26
-  *
27
-  * @param string $text Label text on the button
28
-  * @param string $url Optional. HTTP url to be opened when button is pressed
29
-  * @param string $callback_data Optional. Data to be sent in a callback query to the bot when button is pressed, 1-64 bytes
30
-  * @param string $switch_inline_query Optional. If set, pressing the button will prompt the user to select one of their chats, open that chat and insert the bot‘s username and the specified inline query in the input field. Can be empty, in which case just the bot’s username will be inserted.
31
-  * @param string $switch_inline_query_current_chat Optional. If set, pressing the button will insert the bot‘s username and the specified inline query in the current chat's input field. Can be empty, in which case only the bot’s username will be inserted.
32
-  * @param string $callback_game Optional. Description of the game that will be launched when the user presses the button. NOTE: This type of button must always be the first button in the first row.
33
-  * @return object
34
-  */
25
+   * Add new button to current row.
26
+   *
27
+   * @param string $text Label text on the button
28
+   * @param string $url Optional. HTTP url to be opened when button is pressed
29
+   * @param string $callback_data Optional. Data to be sent in a callback query to the bot when button is pressed, 1-64 bytes
30
+   * @param string $switch_inline_query Optional. If set, pressing the button will prompt the user to select one of their chats, open that chat and insert the bot‘s username and the specified inline query in the input field. Can be empty, in which case just the bot’s username will be inserted.
31
+   * @param string $switch_inline_query_current_chat Optional. If set, pressing the button will insert the bot‘s username and the specified inline query in the current chat's input field. Can be empty, in which case only the bot’s username will be inserted.
32
+   * @param string $callback_game Optional. Description of the game that will be launched when the user presses the button. NOTE: This type of button must always be the first button in the first row.
33
+   * @return object
34
+   */
35 35
   public function addButton(string $text, string $url = '', string $callback_data = '', string $switch_inline_query = '', string $switch_inline_query_current_chat = '', string $callback_game = ''){
36
-    $btn['text'] = $text;
37
-    if($url != '')
38
-      $btn['url'] = $url;
39
-    elseif($callback_data != '')
40
-      $btn['callback_data'] = $callback_data;
41
-    elseif($switch_inline_query != '')
42
-     $btn['switch_inline_query'] = $switch_inline_query;
43
-    elseif($switch_inline_query_current_chat != '')
44
-      $btn['switch_inline_query_current_chat'] = $switch_inline_query_current_chat;
45
-    elseif($callback_game != '')
46
-      $btn['callback_game'] = $callback_game;
47
-    else
48
-      $btn['callback_data'] = $text;
36
+	$btn['text'] = $text;
37
+	if($url != '')
38
+	  $btn['url'] = $url;
39
+	elseif($callback_data != '')
40
+	  $btn['callback_data'] = $callback_data;
41
+	elseif($switch_inline_query != '')
42
+	 $btn['switch_inline_query'] = $switch_inline_query;
43
+	elseif($switch_inline_query_current_chat != '')
44
+	  $btn['switch_inline_query_current_chat'] = $switch_inline_query_current_chat;
45
+	elseif($callback_game != '')
46
+	  $btn['callback_game'] = $callback_game;
47
+	else
48
+	  $btn['callback_data'] = $text;
49 49
       
50
-    $this->inline_keyboard[$this->current_row][] = $btn;
50
+	$this->inline_keyboard[$this->current_row][] = $btn;
51 51
     
52
-    return $this;
52
+	return $this;
53 53
   }
54 54
 
55 55
 }
Please login to merge, or discard this patch.
src/Smoqadam/Keyboard/Standard.php 1 patch
Indentation   +27 added lines, -27 removed lines patch added patch discarded remove patch
@@ -5,47 +5,47 @@
 block discarded – undo
5 5
 class Standard {
6 6
 
7 7
   public
8
-    $keyboard = [],
9
-    $resize_keyboard,
10
-    $one_time_keyboard,
11
-    $selective;
8
+	$keyboard = [],
9
+	$resize_keyboard,
10
+	$one_time_keyboard,
11
+	$selective;
12 12
     
13 13
   private
14
-    $current_row = 0;
14
+	$current_row = 0;
15 15
 
16 16
   public function __construct($resize_keyboard = false, $one_time_keyboard = false, $selective = false) {
17
-    $this->resize_keyboard    = $resize_keyboard;
18
-    $this->one_time_keyboard  = $one_time_keyboard;
19
-    $this->selective          = $selective;
17
+	$this->resize_keyboard    = $resize_keyboard;
18
+	$this->one_time_keyboard  = $one_time_keyboard;
19
+	$this->selective          = $selective;
20 20
   }
21 21
   
22 22
   /**
23
-  * Create new row.
24
-  *
25
-  * @return object Standard
26
-  */
23
+   * Create new row.
24
+   *
25
+   * @return object Standard
26
+   */
27 27
   public function addRow(){
28
-    $this->current_row++;
28
+	$this->current_row++;
29 29
     
30
-    return $this;
30
+	return $this;
31 31
   }
32 32
   
33 33
   /**
34
-  * Add new button to current row.
35
-  *
36
-  * @param string $text 	Text of the button. If none of the optional fields are used, it will be sent to the bot as a message when the button is pressed
37
-  * @param boolean $request_contact Optional. If True, the user's phone number will be sent as a contact when the button is pressed. Available in private chats only
38
-  * @param boolean $request_location Optional. If True, the user's current location will be sent when the button is pressed. Available in private chats only
39
-  * @return object
40
-  */
34
+   * Add new button to current row.
35
+   *
36
+   * @param string $text 	Text of the button. If none of the optional fields are used, it will be sent to the bot as a message when the button is pressed
37
+   * @param boolean $request_contact Optional. If True, the user's phone number will be sent as a contact when the button is pressed. Available in private chats only
38
+   * @param boolean $request_location Optional. If True, the user's current location will be sent when the button is pressed. Available in private chats only
39
+   * @return object
40
+   */
41 41
   public function addButton(string $text, boolean $request_contact = null, boolean $request_location = null){
42
-    $this->keyboard[$this->current_row][] = [
43
-      'text' => $text,
44
-      'request_contact' => ($request_contact != null) ? $request_contact : false,
45
-      'request_location' => ($request_location != null) ? $request_location : false
46
-    ];
42
+	$this->keyboard[$this->current_row][] = [
43
+	  'text' => $text,
44
+	  'request_contact' => ($request_contact != null) ? $request_contact : false,
45
+	  'request_location' => ($request_location != null) ? $request_location : false
46
+	];
47 47
     
48
-    return $this;
48
+	return $this;
49 49
   }
50 50
 
51 51
 }
Please login to merge, or discard this patch.
src/Smoqadam/Keyboard/Remove.php 1 patch
Indentation   +7 added lines, -7 removed lines patch added patch discarded remove patch
@@ -4,16 +4,16 @@
 block discarded – undo
4 4
 
5 5
 class Remove {
6 6
     
7
-    public
8
-        $remove_keyboard = true,
9
-        $selective;
7
+	public
8
+		$remove_keyboard = true,
9
+		$selective;
10 10
         
11
-    /*
11
+	/*
12 12
     * Telegram clients will remove the current custom keyboard and display the default letter-keyboard.
13 13
     *
14 14
     * @param boolean $selective Optional. Use this parameter if you want to remove the keyboard for specific users only. Targets: 1) users that are @mentioned in the text of the Message object; 2) if the bot's message is a reply (has reply_to_message_id), sender of the original message.
15 15
     */
16
-    public function __construct($selective = false){
17
-        $this->selective        = $selective;
18
-    }
16
+	public function __construct($selective = false){
17
+		$this->selective        = $selective;
18
+	}
19 19
 }
20 20
\ No newline at end of file
Please login to merge, or discard this patch.
src/Smoqadam/Trigger.php 1 patch
Indentation   +4 added lines, -4 removed lines patch added patch discarded remove patch
@@ -5,12 +5,12 @@
 block discarded – undo
5 5
 class Trigger {
6 6
   
7 7
   public
8
-    $pattern,
9
-    $callback;
8
+	$pattern,
9
+	$callback;
10 10
 
11 11
   public function __construct($pattern, $callback) {
12
-    $this->pattern  = $pattern;
13
-    $this->callback = $callback;
12
+	$this->pattern  = $pattern;
13
+	$this->callback = $callback;
14 14
   }
15 15
 
16 16
 }
Please login to merge, or discard this patch.
src/Smoqadam/Input/TextMessageContent.php 1 patch
Indentation   +6 added lines, -6 removed lines patch added patch discarded remove patch
@@ -6,14 +6,14 @@
 block discarded – undo
6 6
 class TextMessageContent {
7 7
 
8 8
   public
9
-    $message_text,
10
-    $parse_mode,
11
-    $disable_web_page_preview;
9
+	$message_text,
10
+	$parse_mode,
11
+	$disable_web_page_preview;
12 12
 
13 13
   public function __construct($message_text, $parse_mode = Telegram::PARSE_MARKDOWN, $disable_web_page_preview = false) {
14
-    $this->message_text             = $message_text;
15
-    $this->parse_mode               = $parse_mode;
16
-    $this->disable_web_page_preview = $disable_web_page_preview;
14
+	$this->message_text             = $message_text;
15
+	$this->parse_mode               = $parse_mode;
16
+	$this->disable_web_page_preview = $disable_web_page_preview;
17 17
   }
18 18
 
19 19
 }
Please login to merge, or discard this patch.
src/Smoqadam/Telegram.php 1 patch
Indentation   +516 added lines, -516 removed lines patch added patch discarded remove patch
@@ -12,521 +12,521 @@
 block discarded – undo
12 12
 
13 13
 class Telegram {
14 14
 
15
-    const PARSE_MARKDOWN = 'Markdown';
16
-    const PARSE_HTML     = 'HTML';
17
-
18
-    const ACTION_TYPING         = 'typing';
19
-    const ACTION_UPLOAD_PHOTO   = 'upload_photo';
20
-    const ACTION_RECORD_VIDEO   = 'record_video';
21
-    const ACTION_UPLOAD_VIDEO   = 'upload_video';
22
-    const ACTION_RECORD_AUDIO   = 'record_audio';
23
-    const ACTION_UPLOAD_AUDIO   = 'upload_audio';
24
-    const ACTION_UPLOAD_DOC     = 'upload_document';
25
-    const ACTION_FIND_LOCATION  = 'find_location';
26
-
27
-    public $api = 'https://api.telegram.org/bot';
28
-
29
-    /**
30
-     * returned json from telegram api parse to object and save to result
31
-     * @var
32
-     */
33
-    public $result;
34
-
35
-    /**
36
-     * @name State of bot
37
-     * state of bot
38
-     * @var object
39
-     */
40
-    public $state;
41
-
42
-    /**
43
-     * commands in regex and callback
44
-     * @var array
45
-     */
46
-    private $commands = [];
47
-
48
-    /**
49
-     * InlineQuery in regex and callback
50
-     * @var array
51
-     */
52
-    private $inlines = [];
53
-
54
-    /**
55
-     * callbacks
56
-     * @var array
57
-     */
58
-    private $callbacks = [];
59
-
60
-    /**
61
-     * available telegram bot commands
62
-     * @var array
63
-     */
64
-    private $available_commands = [
65
-        'getMe',
66
-        'sendMessage',
67
-        'forwardMessage',
68
-        'sendPhoto',
69
-        'sendAudio',
70
-        'sendDocument',
71
-        'sendSticker',
72
-        'sendVideo',
73
-        'sendLocation',
74
-        'sendChatAction',
75
-        'getUserProfilePhotos',
76
-        'answerInlineQuery',
77
-        'getUpdates',
78
-        'setWebhook',
79
-    ];
80
-
81
-    /**
82
-     * pre patterns you can use in regex
83
-     * @var array
84
-     */
85
-    private $patterns = [
86
-        ':any' => '.*',
87
-        ':num' => '[0-9]{0,}',
88
-        ':str' => '[a-zA-z]{0,}',
89
-    ];
90
-
91
-    /**
92
-     *
93
-     * @param String $token Telegram api token , taken by botfather
94
-     */
95
-    public function __construct($token) {
96
-        $this->api .= $token;
97
-    }
98
-
99
-    /**
100
-     * add new command to the bot
101
-     * @param String $cmd
102
-     * @param \Closure $func
103
-     */
104
-    public function cmd($cmd, $func) {
105
-        $this->commands[] = new Trigger($cmd, $func);
106
-    }
107
-
108
-
109
-    public function PDO(){
110
-
111
-        $servername ='YOUR_SERVER_NAME';
112
-        $username = 'YOUR_USERNAME';
113
-        $password ='YOUR_PASSWORD';
114
-        $dbname = 'YOUR_DATABASE_NAME';
115
-        try {
116
-            $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password, [PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"]);
117
-            $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
118
-
119
-            return $conn;
120
-        }
121
-        catch(PDOException $e)
122
-        {
123
-            return $e->getMessage();
124
-        }
125
-    }
126
-
127
-    /**
128
-     * add new InlineQuery to the bot
129
-     * @param String $cmd
130
-     * @param \Closure $func
131
-     */
132
-    public function inlineQuery($cmd, $func) {
133
-        $this->inlines[] = new Trigger($cmd, $func);
134
-    }
135
-
136
-    /**
137
-     * this method check for received payload(command, inlinequery and so on) and
138
-     * then execute the correct function
139
-     *
140
-     * @param bool $sleep
141
-     */
142
-    public function run($sleep = false) {
143
-        $result = $this->getUpdates();
144
-        while (true) {
145
-            $update_id = isset($result->update_id) ? $result->update_id : 1;
146
-            $result = $this->getUpdates($update_id + 1);
147
-
148
-            $this->processPayload($result);
149
-
150
-            if ($sleep !== false)
151
-                sleep($sleep);
152
-        }
153
-    }
154
-
155
-    /**
156
-     * this method used for setWebhook sended payload
157
-     */
158
-    public function process($payload) {
159
-        $result = $this->convertToObject($payload, true);
160
-
161
-        return $this->processPayload($result);
162
-    }
163
-
164
-    private function processPayload($result) {
165
-        if ($result) {
166
-            try {
167
-                $this->result = $result;
168
-
169
-                // now i select the right triggers for payload received by Telegram
170
-                if( isset($this->result->message->text) ) {
171
-                    $payload = $this->result->message->text;
172
-                    $triggers = $this->commands;
173
-                } elseif ( isset($this->result->inline_query) ) {
174
-                    $payload = $this->result->inline_query->query;
175
-                    $triggers = $this->inlines;
176
-                } else {
177
-                    throw new \Exception("Error Processing Request", 1);
178
-                }
179
-
180
-                $args = null;
181
-
182
-                foreach ($triggers as &$trigger) {
183
-                    // replace public patterns to regex pattern
184
-                    $searchs = array_keys($this->patterns);
185
-                    $replaces = array_values($this->patterns);
186
-                    $pattern = str_replace($searchs, $replaces, $trigger->pattern);
187
-
188
-                    //find args pattern
189
-                    $args = $this->getArgs($pattern, $payload);
190
-
191
-                    $pattern = '/^' . $pattern . '/i';
192
-
193
-                    preg_match($pattern, $payload, $matches);
194
-
195
-                    if (isset($matches[0])) {
196
-                        $func = $trigger->callback;
197
-                        return call_user_func($func, $args);
198
-                    }
199
-                }
200
-            } catch (\Exception $e) {
201
-                error_log($e->getMessage());
202
-                echo "\r\n Exception :: " . $e->getMessage();
203
-            }
204
-        } else {
205
-            echo "\r\nNo new message\r\n";
206
-        }
207
-    }
208
-
209
-    /**
210
-     * get arguments part in regex
211
-     * @param $pattern
212
-     * @param $payload
213
-     * @return mixed|null
214
-     */
215
-    private function getArgs(&$pattern, $payload) {
216
-        $args = null;
217
-        // if command has argument
218
-        if (preg_match('/<<.*>>/', $pattern, $matches)) {
219
-
220
-            $args_pattern = $matches[0];
221
-            //remove << and >> from patterns
222
-            $tmp_args_pattern = str_replace(['<<', '>>'], ['(', ')'], $pattern);
223
-
224
-            //if args set
225
-            if (preg_match('/' . $tmp_args_pattern . '/i', $payload, $matches)) {
226
-                //remove first element
227
-                array_shift($matches);
228
-                if (isset($matches[0])) {
229
-                    //set args
230
-                    $args = array_shift($matches);
231
-
232
-                    //remove args pattern from main pattern
233
-                    $pattern = str_replace($args_pattern, '', $pattern);
234
-                }
235
-            }
236
-        }
237
-        return $args;
238
-    }
239
-
240
-    /**
241
-     * execute telegram api commands
242
-     * @param $command
243
-     * @param array $params
244
-     */
245
-    private function exec($command, $params = []) {
246
-        if (in_array($command, $this->available_commands)) {
247
-            // convert json to array then get the last messages info
248
-            $output = json_decode($this->curl_get_contents($this->api . '/' . $command, $params), true);
249
-
250
-            return $this->convertToObject($output);
251
-        } else {
252
-            echo 'command not found';
253
-        }
254
-    }
255
-
256
-    private function convertToObject($jsonObject , $webhook = false) {
257
-        if( ! $webhook) {
258
-            if ($jsonObject['ok']) {
259
-                //error_log(print_r($jsonObject, true));
260
-
261
-                // remove unwanted array elements
262
-                $output = end($jsonObject);
263
-
264
-                $result = is_array($output) ? end($output) : $output;
265
-                if ( ! empty($result)) {
266
-                    // convert to object
267
-                    return json_decode(json_encode($result));
268
-                }
269
-            }
270
-        } else {
271
-            return json_decode(json_encode($jsonObject));
272
-        }
273
-    }
274
-
275
-    /**
276
-     * get the $url content with CURL
277
-     * @param $url
278
-     * @param $params
279
-     * @return mixed
280
-     */
281
-    private function curl_get_contents($url, $params) {
282
-        $ch = curl_init();
283
-
284
-        curl_setopt($ch, CURLOPT_URL, $url);
285
-        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
286
-        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
287
-        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
288
-        curl_setopt($ch, CURLOPT_POST, count($params));
289
-        curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
290
-
291
-        $result = curl_exec($ch);
292
-
293
-        curl_close($ch);
294
-
295
-        return $result;
296
-    }
297
-
298
-    /**
299
-     * Get current chat id
300
-     * @param null $chat_id
301
-     * @return int
302
-     */
303
-    public function getChatId($chat_id = null) {
304
-        try {
305
-            if ($chat_id)
306
-                return $chat_id;
307
-
308
-            if( isset($this->result->message) ) {
309
-                return $this->result->message->chat->id;
310
-            } elseif ( isset($this->result->inline_query) ) {
311
-                return $this->result->inline_query->from->id;
312
-            } else {
313
-                throw new \Exception("Error Processing Request", 1);
314
-            }
315
-        } catch (\Exception $e) {
316
-            error_log($e->getMessage());
317
-        }
318
-    }
319
-
320
-    /**
321
-     * @param null $offset
322
-     * @param int $limit
323
-     * @param int $timeout
324
-     */
325
-    public function getUpdates($offset = null, $limit = 1, $timeout = 1) {
326
-        return $this->exec('getUpdates', [
327
-            'offset' => $offset,
328
-            'limit' => $limit,
329
-            'timeout' => $timeout
330
-        ]);
331
-    }
332
-
333
-    /**
334
-     * send message
335
-     * @param $text
336
-     * @param $chat_id
337
-     * @param bool $disable_web_page_preview
338
-     * @param null $reply_to_message_id
339
-     * @param null $reply_markup
340
-     */
341
-    public function sendMessage($text, $chat_id = null, $disable_web_page_preview = false, $reply_to_message_id = null, $reply_markup = null, $parse_mode = null) {
342
-        $this->sendChatAction(self::ACTION_TYPING, $chat_id);
343
-        return $this->exec('sendMessage', [
344
-            'chat_id' => $this->getChatId($chat_id),
345
-            'text' => $text,
346
-            'parse_mode' => $parse_mode,
347
-            'disable_web_page_preview' => $disable_web_page_preview,
348
-            'reply_to_message_id' => $reply_to_message_id,
349
-            'reply_markup' => json_encode($reply_markup)
350
-        ]);
351
-    }
352
-
353
-    /**
354
-     * Get me
355
-     */
356
-    public function getMe() {
357
-        return $this->exec('getMe');
358
-    }
359
-
360
-    /**
361
-     * @param $from_id
362
-     * @param $message_id
363
-     * @param null $chat_id
364
-     */
365
-    public function forwardMessage($from_id, $message_id, $chat_id = null) {
366
-        return $this->exec('forwardMessage', [
367
-            'chat_id' => $this->getChatId($chat_id),
368
-            'from_chat_id' => $from_id,
369
-            'message_id' => $message_id,
370
-        ]);
371
-    }
372
-
373
-    /**
374
-     * @param $photo photo file patch
375
-     * @param null $chat_id
376
-     * @param null $caption
377
-     * @param null $reply_to_message_id
378
-     * @param null $reply_markup
379
-     */
380
-    public function sendPhoto($photo, $chat_id = null, $caption = null, $reply_to_message_id = null, $reply_markup = null, $parse_mode = null) {
381
-        $res = $this->exec('sendPhoto', [
382
-            'chat_id' => $this->getChatId($chat_id),
383
-            'photo' => $photo,
384
-            'parse_mode' => $parse_mode,
385
-            'caption' => $caption,
386
-            'reply_to_message_id' => $reply_to_message_id,
387
-            'reply_markup' => json_encode($reply_markup)
388
-        ]);
389
-
390
-        return $res;
391
-    }
392
-
393
-    /**
394
-     * @param $video video file path
395
-     * @param null $chat_id
396
-     * @param null $reply_to_message_id
397
-     * @param null $reply_markup
398
-     */
399
-    public function sendVideo($video, $chat_id = null, $reply_to_message_id = null, $reply_markup = null, $parse_mode = null) {
400
-        $res = $this->exec('sendVideo', [
401
-            'chat_id' => $this->getChatId($chat_id),
402
-            'video' => $video,
403
-            'parse_mode' => $parse_mode,
404
-            'reply_to_message_id' => $reply_to_message_id,
405
-            'reply_markup' => json_encode($reply_markup)
406
-        ]);
407
-
408
-        return $res;
409
-    }
410
-
411
-    /**
412
-     *
413
-     * @param $sticker
414
-     * @param null $chat_id
415
-     * @param null $reply_to_message_id
416
-     * @param null $reply_markup
417
-     */
418
-    public function sendSticker($sticker, $chat_id = null, $reply_to_message_id = null, $reply_markup = null) {
419
-        $res = $this->exec('sendSticker', [
420
-            'chat_id' => $this->getChatId($chat_id),
421
-            'sticker' => $sticker,
422
-            'reply_to_message_id' => $reply_to_message_id,
423
-            'reply_markup' => json_encode($reply_markup)
424
-        ]);
425
-
426
-        return $res;
427
-        // as soons as possible
428
-    }
429
-
430
-    /**
431
-     * @param $latitude
432
-     * @param $longitude
433
-     * @param null $chat_id
434
-     * @param null $reply_to_message_id
435
-     * @param null $reply_markup
436
-     */
437
-    public function sendLocation($latitude, $longitude, $chat_id = null, $reply_to_message_id = null, $reply_markup = null) {
438
-        $res = $this->exec('sendLocation', [
439
-            'chat_id' => $this->getChatId($chat_id),
440
-            'latitude' => $latitude,
441
-            'longitude' => $longitude,
442
-            'reply_to_message_id' => $reply_to_message_id,
443
-            'reply_markup' => json_encode($reply_markup)
444
-        ]);
445
-
446
-        return $res;
447
-    }
448
-
449
-    /**
450
-     * @param $document
451
-     * @param null $chat_id
452
-     * @param null $reply_to_message_id
453
-     * @param null $reply_markup
454
-     */
455
-    public function sendDocument($document, $chat_id = null, $reply_to_message_id = null, $reply_markup = null) {
456
-        $res = $this->exec('sendDocument', [
457
-            'chat_id' => $this->getChatId($chat_id),
458
-            'document' => $document,
459
-            'reply_to_message_id' => $reply_to_message_id,
460
-            'reply_markup' => json_encode($reply_markup)
461
-        ]);
462
-
463
-        return $res;
464
-    }
465
-
466
-    public function sendAudio($audio, $chat_id = null, $reply_to_message_id = null, $reply_markup = null) {
467
-        $res = $this->exec('sendAudio', [
468
-            'chat_id' => $this->getChatId($chat_id),
469
-            'audio' => $audio,
470
-            'reply_to_message_id' => $reply_to_message_id,
471
-            'reply_markup' => json_encode($reply_markup)
472
-        ]);
473
-
474
-        return $res;
475
-    }
476
-
477
-    /**
478
-     * send chat action : Telegram::ACTION_TYPING , ...
479
-     * @param $action
480
-     * @param null $chat_id
481
-     */
482
-    public function sendChatAction($action, $chat_id = null) {
483
-        $res = $this->exec('sendChatAction', [
484
-            'chat_id' => $this->getChatId($chat_id),
485
-            'action' => $action
486
-        ]);
487
-
488
-        return $res;
489
-    }
490
-
491
-    /**
492
-     * @param $user_id
493
-     * @param null $offset
494
-     * @param null $limit
495
-     */
496
-    public function getUserProfilePhotos($user_id, $offset = null, $limit = null) {
497
-        $res = $this->exec('getUserProfilePhotos', [
498
-            'user_id' => $user_id,
499
-            'offset' => $offset,
500
-            'limit' => $limit
501
-        ]);
502
-
503
-        return $res;
504
-    }
505
-
506
-
507
-    public function answerInlineQuery($inline_query_id, $results, $cache_time = 0, $is_personal = false, $next_offset = '', $switch_pm_text = '', $switch_pm_parameter = '') {
508
-        $res = $this->exec('answerInlineQuery', [
509
-            'inline_query_id' => $inline_query_id,
510
-            'results' => json_encode($results),
511
-            'cache_time' => $cache_time,
512
-            'is_personal' => $is_personal,
513
-            'next_offset' => $next_offset,
514
-            'switch_pm_text' => $switch_pm_text,
515
-            'switch_pm_parameter' => $switch_pm_parameter
516
-        ]);
517
-
518
-        return $res;
519
-    }
520
-
521
-    /**
522
-     * @param $url
523
-     */
524
-    public function setWebhook($url) {
525
-        $res = $this->exec('setWebhook', [
526
-            'url' => $url
527
-        ]);
528
-
529
-        return $res;
530
-    }
15
+	const PARSE_MARKDOWN = 'Markdown';
16
+	const PARSE_HTML     = 'HTML';
17
+
18
+	const ACTION_TYPING         = 'typing';
19
+	const ACTION_UPLOAD_PHOTO   = 'upload_photo';
20
+	const ACTION_RECORD_VIDEO   = 'record_video';
21
+	const ACTION_UPLOAD_VIDEO   = 'upload_video';
22
+	const ACTION_RECORD_AUDIO   = 'record_audio';
23
+	const ACTION_UPLOAD_AUDIO   = 'upload_audio';
24
+	const ACTION_UPLOAD_DOC     = 'upload_document';
25
+	const ACTION_FIND_LOCATION  = 'find_location';
26
+
27
+	public $api = 'https://api.telegram.org/bot';
28
+
29
+	/**
30
+	 * returned json from telegram api parse to object and save to result
31
+	 * @var
32
+	 */
33
+	public $result;
34
+
35
+	/**
36
+	 * @name State of bot
37
+	 * state of bot
38
+	 * @var object
39
+	 */
40
+	public $state;
41
+
42
+	/**
43
+	 * commands in regex and callback
44
+	 * @var array
45
+	 */
46
+	private $commands = [];
47
+
48
+	/**
49
+	 * InlineQuery in regex and callback
50
+	 * @var array
51
+	 */
52
+	private $inlines = [];
53
+
54
+	/**
55
+	 * callbacks
56
+	 * @var array
57
+	 */
58
+	private $callbacks = [];
59
+
60
+	/**
61
+	 * available telegram bot commands
62
+	 * @var array
63
+	 */
64
+	private $available_commands = [
65
+		'getMe',
66
+		'sendMessage',
67
+		'forwardMessage',
68
+		'sendPhoto',
69
+		'sendAudio',
70
+		'sendDocument',
71
+		'sendSticker',
72
+		'sendVideo',
73
+		'sendLocation',
74
+		'sendChatAction',
75
+		'getUserProfilePhotos',
76
+		'answerInlineQuery',
77
+		'getUpdates',
78
+		'setWebhook',
79
+	];
80
+
81
+	/**
82
+	 * pre patterns you can use in regex
83
+	 * @var array
84
+	 */
85
+	private $patterns = [
86
+		':any' => '.*',
87
+		':num' => '[0-9]{0,}',
88
+		':str' => '[a-zA-z]{0,}',
89
+	];
90
+
91
+	/**
92
+	 *
93
+	 * @param String $token Telegram api token , taken by botfather
94
+	 */
95
+	public function __construct($token) {
96
+		$this->api .= $token;
97
+	}
98
+
99
+	/**
100
+	 * add new command to the bot
101
+	 * @param String $cmd
102
+	 * @param \Closure $func
103
+	 */
104
+	public function cmd($cmd, $func) {
105
+		$this->commands[] = new Trigger($cmd, $func);
106
+	}
107
+
108
+
109
+	public function PDO(){
110
+
111
+		$servername ='YOUR_SERVER_NAME';
112
+		$username = 'YOUR_USERNAME';
113
+		$password ='YOUR_PASSWORD';
114
+		$dbname = 'YOUR_DATABASE_NAME';
115
+		try {
116
+			$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password, [PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"]);
117
+			$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
118
+
119
+			return $conn;
120
+		}
121
+		catch(PDOException $e)
122
+		{
123
+			return $e->getMessage();
124
+		}
125
+	}
126
+
127
+	/**
128
+	 * add new InlineQuery to the bot
129
+	 * @param String $cmd
130
+	 * @param \Closure $func
131
+	 */
132
+	public function inlineQuery($cmd, $func) {
133
+		$this->inlines[] = new Trigger($cmd, $func);
134
+	}
135
+
136
+	/**
137
+	 * this method check for received payload(command, inlinequery and so on) and
138
+	 * then execute the correct function
139
+	 *
140
+	 * @param bool $sleep
141
+	 */
142
+	public function run($sleep = false) {
143
+		$result = $this->getUpdates();
144
+		while (true) {
145
+			$update_id = isset($result->update_id) ? $result->update_id : 1;
146
+			$result = $this->getUpdates($update_id + 1);
147
+
148
+			$this->processPayload($result);
149
+
150
+			if ($sleep !== false)
151
+				sleep($sleep);
152
+		}
153
+	}
154
+
155
+	/**
156
+	 * this method used for setWebhook sended payload
157
+	 */
158
+	public function process($payload) {
159
+		$result = $this->convertToObject($payload, true);
160
+
161
+		return $this->processPayload($result);
162
+	}
163
+
164
+	private function processPayload($result) {
165
+		if ($result) {
166
+			try {
167
+				$this->result = $result;
168
+
169
+				// now i select the right triggers for payload received by Telegram
170
+				if( isset($this->result->message->text) ) {
171
+					$payload = $this->result->message->text;
172
+					$triggers = $this->commands;
173
+				} elseif ( isset($this->result->inline_query) ) {
174
+					$payload = $this->result->inline_query->query;
175
+					$triggers = $this->inlines;
176
+				} else {
177
+					throw new \Exception("Error Processing Request", 1);
178
+				}
179
+
180
+				$args = null;
181
+
182
+				foreach ($triggers as &$trigger) {
183
+					// replace public patterns to regex pattern
184
+					$searchs = array_keys($this->patterns);
185
+					$replaces = array_values($this->patterns);
186
+					$pattern = str_replace($searchs, $replaces, $trigger->pattern);
187
+
188
+					//find args pattern
189
+					$args = $this->getArgs($pattern, $payload);
190
+
191
+					$pattern = '/^' . $pattern . '/i';
192
+
193
+					preg_match($pattern, $payload, $matches);
194
+
195
+					if (isset($matches[0])) {
196
+						$func = $trigger->callback;
197
+						return call_user_func($func, $args);
198
+					}
199
+				}
200
+			} catch (\Exception $e) {
201
+				error_log($e->getMessage());
202
+				echo "\r\n Exception :: " . $e->getMessage();
203
+			}
204
+		} else {
205
+			echo "\r\nNo new message\r\n";
206
+		}
207
+	}
208
+
209
+	/**
210
+	 * get arguments part in regex
211
+	 * @param $pattern
212
+	 * @param $payload
213
+	 * @return mixed|null
214
+	 */
215
+	private function getArgs(&$pattern, $payload) {
216
+		$args = null;
217
+		// if command has argument
218
+		if (preg_match('/<<.*>>/', $pattern, $matches)) {
219
+
220
+			$args_pattern = $matches[0];
221
+			//remove << and >> from patterns
222
+			$tmp_args_pattern = str_replace(['<<', '>>'], ['(', ')'], $pattern);
223
+
224
+			//if args set
225
+			if (preg_match('/' . $tmp_args_pattern . '/i', $payload, $matches)) {
226
+				//remove first element
227
+				array_shift($matches);
228
+				if (isset($matches[0])) {
229
+					//set args
230
+					$args = array_shift($matches);
231
+
232
+					//remove args pattern from main pattern
233
+					$pattern = str_replace($args_pattern, '', $pattern);
234
+				}
235
+			}
236
+		}
237
+		return $args;
238
+	}
239
+
240
+	/**
241
+	 * execute telegram api commands
242
+	 * @param $command
243
+	 * @param array $params
244
+	 */
245
+	private function exec($command, $params = []) {
246
+		if (in_array($command, $this->available_commands)) {
247
+			// convert json to array then get the last messages info
248
+			$output = json_decode($this->curl_get_contents($this->api . '/' . $command, $params), true);
249
+
250
+			return $this->convertToObject($output);
251
+		} else {
252
+			echo 'command not found';
253
+		}
254
+	}
255
+
256
+	private function convertToObject($jsonObject , $webhook = false) {
257
+		if( ! $webhook) {
258
+			if ($jsonObject['ok']) {
259
+				//error_log(print_r($jsonObject, true));
260
+
261
+				// remove unwanted array elements
262
+				$output = end($jsonObject);
263
+
264
+				$result = is_array($output) ? end($output) : $output;
265
+				if ( ! empty($result)) {
266
+					// convert to object
267
+					return json_decode(json_encode($result));
268
+				}
269
+			}
270
+		} else {
271
+			return json_decode(json_encode($jsonObject));
272
+		}
273
+	}
274
+
275
+	/**
276
+	 * get the $url content with CURL
277
+	 * @param $url
278
+	 * @param $params
279
+	 * @return mixed
280
+	 */
281
+	private function curl_get_contents($url, $params) {
282
+		$ch = curl_init();
283
+
284
+		curl_setopt($ch, CURLOPT_URL, $url);
285
+		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
286
+		curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
287
+		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
288
+		curl_setopt($ch, CURLOPT_POST, count($params));
289
+		curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
290
+
291
+		$result = curl_exec($ch);
292
+
293
+		curl_close($ch);
294
+
295
+		return $result;
296
+	}
297
+
298
+	/**
299
+	 * Get current chat id
300
+	 * @param null $chat_id
301
+	 * @return int
302
+	 */
303
+	public function getChatId($chat_id = null) {
304
+		try {
305
+			if ($chat_id)
306
+				return $chat_id;
307
+
308
+			if( isset($this->result->message) ) {
309
+				return $this->result->message->chat->id;
310
+			} elseif ( isset($this->result->inline_query) ) {
311
+				return $this->result->inline_query->from->id;
312
+			} else {
313
+				throw new \Exception("Error Processing Request", 1);
314
+			}
315
+		} catch (\Exception $e) {
316
+			error_log($e->getMessage());
317
+		}
318
+	}
319
+
320
+	/**
321
+	 * @param null $offset
322
+	 * @param int $limit
323
+	 * @param int $timeout
324
+	 */
325
+	public function getUpdates($offset = null, $limit = 1, $timeout = 1) {
326
+		return $this->exec('getUpdates', [
327
+			'offset' => $offset,
328
+			'limit' => $limit,
329
+			'timeout' => $timeout
330
+		]);
331
+	}
332
+
333
+	/**
334
+	 * send message
335
+	 * @param $text
336
+	 * @param $chat_id
337
+	 * @param bool $disable_web_page_preview
338
+	 * @param null $reply_to_message_id
339
+	 * @param null $reply_markup
340
+	 */
341
+	public function sendMessage($text, $chat_id = null, $disable_web_page_preview = false, $reply_to_message_id = null, $reply_markup = null, $parse_mode = null) {
342
+		$this->sendChatAction(self::ACTION_TYPING, $chat_id);
343
+		return $this->exec('sendMessage', [
344
+			'chat_id' => $this->getChatId($chat_id),
345
+			'text' => $text,
346
+			'parse_mode' => $parse_mode,
347
+			'disable_web_page_preview' => $disable_web_page_preview,
348
+			'reply_to_message_id' => $reply_to_message_id,
349
+			'reply_markup' => json_encode($reply_markup)
350
+		]);
351
+	}
352
+
353
+	/**
354
+	 * Get me
355
+	 */
356
+	public function getMe() {
357
+		return $this->exec('getMe');
358
+	}
359
+
360
+	/**
361
+	 * @param $from_id
362
+	 * @param $message_id
363
+	 * @param null $chat_id
364
+	 */
365
+	public function forwardMessage($from_id, $message_id, $chat_id = null) {
366
+		return $this->exec('forwardMessage', [
367
+			'chat_id' => $this->getChatId($chat_id),
368
+			'from_chat_id' => $from_id,
369
+			'message_id' => $message_id,
370
+		]);
371
+	}
372
+
373
+	/**
374
+	 * @param $photo photo file patch
375
+	 * @param null $chat_id
376
+	 * @param null $caption
377
+	 * @param null $reply_to_message_id
378
+	 * @param null $reply_markup
379
+	 */
380
+	public function sendPhoto($photo, $chat_id = null, $caption = null, $reply_to_message_id = null, $reply_markup = null, $parse_mode = null) {
381
+		$res = $this->exec('sendPhoto', [
382
+			'chat_id' => $this->getChatId($chat_id),
383
+			'photo' => $photo,
384
+			'parse_mode' => $parse_mode,
385
+			'caption' => $caption,
386
+			'reply_to_message_id' => $reply_to_message_id,
387
+			'reply_markup' => json_encode($reply_markup)
388
+		]);
389
+
390
+		return $res;
391
+	}
392
+
393
+	/**
394
+	 * @param $video video file path
395
+	 * @param null $chat_id
396
+	 * @param null $reply_to_message_id
397
+	 * @param null $reply_markup
398
+	 */
399
+	public function sendVideo($video, $chat_id = null, $reply_to_message_id = null, $reply_markup = null, $parse_mode = null) {
400
+		$res = $this->exec('sendVideo', [
401
+			'chat_id' => $this->getChatId($chat_id),
402
+			'video' => $video,
403
+			'parse_mode' => $parse_mode,
404
+			'reply_to_message_id' => $reply_to_message_id,
405
+			'reply_markup' => json_encode($reply_markup)
406
+		]);
407
+
408
+		return $res;
409
+	}
410
+
411
+	/**
412
+	 *
413
+	 * @param $sticker
414
+	 * @param null $chat_id
415
+	 * @param null $reply_to_message_id
416
+	 * @param null $reply_markup
417
+	 */
418
+	public function sendSticker($sticker, $chat_id = null, $reply_to_message_id = null, $reply_markup = null) {
419
+		$res = $this->exec('sendSticker', [
420
+			'chat_id' => $this->getChatId($chat_id),
421
+			'sticker' => $sticker,
422
+			'reply_to_message_id' => $reply_to_message_id,
423
+			'reply_markup' => json_encode($reply_markup)
424
+		]);
425
+
426
+		return $res;
427
+		// as soons as possible
428
+	}
429
+
430
+	/**
431
+	 * @param $latitude
432
+	 * @param $longitude
433
+	 * @param null $chat_id
434
+	 * @param null $reply_to_message_id
435
+	 * @param null $reply_markup
436
+	 */
437
+	public function sendLocation($latitude, $longitude, $chat_id = null, $reply_to_message_id = null, $reply_markup = null) {
438
+		$res = $this->exec('sendLocation', [
439
+			'chat_id' => $this->getChatId($chat_id),
440
+			'latitude' => $latitude,
441
+			'longitude' => $longitude,
442
+			'reply_to_message_id' => $reply_to_message_id,
443
+			'reply_markup' => json_encode($reply_markup)
444
+		]);
445
+
446
+		return $res;
447
+	}
448
+
449
+	/**
450
+	 * @param $document
451
+	 * @param null $chat_id
452
+	 * @param null $reply_to_message_id
453
+	 * @param null $reply_markup
454
+	 */
455
+	public function sendDocument($document, $chat_id = null, $reply_to_message_id = null, $reply_markup = null) {
456
+		$res = $this->exec('sendDocument', [
457
+			'chat_id' => $this->getChatId($chat_id),
458
+			'document' => $document,
459
+			'reply_to_message_id' => $reply_to_message_id,
460
+			'reply_markup' => json_encode($reply_markup)
461
+		]);
462
+
463
+		return $res;
464
+	}
465
+
466
+	public function sendAudio($audio, $chat_id = null, $reply_to_message_id = null, $reply_markup = null) {
467
+		$res = $this->exec('sendAudio', [
468
+			'chat_id' => $this->getChatId($chat_id),
469
+			'audio' => $audio,
470
+			'reply_to_message_id' => $reply_to_message_id,
471
+			'reply_markup' => json_encode($reply_markup)
472
+		]);
473
+
474
+		return $res;
475
+	}
476
+
477
+	/**
478
+	 * send chat action : Telegram::ACTION_TYPING , ...
479
+	 * @param $action
480
+	 * @param null $chat_id
481
+	 */
482
+	public function sendChatAction($action, $chat_id = null) {
483
+		$res = $this->exec('sendChatAction', [
484
+			'chat_id' => $this->getChatId($chat_id),
485
+			'action' => $action
486
+		]);
487
+
488
+		return $res;
489
+	}
490
+
491
+	/**
492
+	 * @param $user_id
493
+	 * @param null $offset
494
+	 * @param null $limit
495
+	 */
496
+	public function getUserProfilePhotos($user_id, $offset = null, $limit = null) {
497
+		$res = $this->exec('getUserProfilePhotos', [
498
+			'user_id' => $user_id,
499
+			'offset' => $offset,
500
+			'limit' => $limit
501
+		]);
502
+
503
+		return $res;
504
+	}
505
+
506
+
507
+	public function answerInlineQuery($inline_query_id, $results, $cache_time = 0, $is_personal = false, $next_offset = '', $switch_pm_text = '', $switch_pm_parameter = '') {
508
+		$res = $this->exec('answerInlineQuery', [
509
+			'inline_query_id' => $inline_query_id,
510
+			'results' => json_encode($results),
511
+			'cache_time' => $cache_time,
512
+			'is_personal' => $is_personal,
513
+			'next_offset' => $next_offset,
514
+			'switch_pm_text' => $switch_pm_text,
515
+			'switch_pm_parameter' => $switch_pm_parameter
516
+		]);
517
+
518
+		return $res;
519
+	}
520
+
521
+	/**
522
+	 * @param $url
523
+	 */
524
+	public function setWebhook($url) {
525
+		$res = $this->exec('setWebhook', [
526
+			'url' => $url
527
+		]);
528
+
529
+		return $res;
530
+	}
531 531
 
532 532
 }
Please login to merge, or discard this patch.