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