Completed
Pull Request — master (#7)
by
unknown
01:37
created
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.