Completed
Pull Request — master (#4)
by
unknown
02:10
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   +480 added lines, -480 removed lines patch added patch discarded remove patch
@@ -23,487 +23,487 @@
 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
-     */
321
-    public function sendMessage($text, $chat_id = null, $disable_web_page_preview = false, $reply_to_message_id = null, $reply_markup = null) {
322
-        $this->sendChatAction(self::ACTION_TYPING, $chat_id);
323
-        return $this->exec('sendMessage', [
324
-            'chat_id' => $this->getChatId($chat_id),
325
-            'text' => $text,
326
-            'disable_web_page_preview' => $disable_web_page_preview,
327
-            'reply_to_message_id' => $reply_to_message_id,
328
-            'reply_markup' => $reply_markup
329
-        ]);
330
-    }
331
-
332
-    /**
333
-     * Get me
334
-     */
335
-    public function getMe() {
336
-        return $this->exec('getMe');
337
-    }
338
-
339
-    /**
340
-     * @param $from_id
341
-     * @param $message_id
342
-     * @param null $chat_id
343
-     */
344
-    public function forwardMessage($from_id, $message_id, $chat_id = null) {
345
-        return $this->exec('forwardMessage', [
346
-            'chat_id' => $this->getChatId($chat_id),
347
-            'from_chat_id' => $from_id,
348
-            'message_id' => $message_id,
349
-        ]);
350
-    }
351
-
352
-    /**
353
-     * @param $photo photo file patch
354
-     * @param null $chat_id
355
-     * @param null $caption
356
-     * @param null $reply_to_message_id
357
-     * @param null $reply_markup
358
-     */
359
-    public function sendPhoto($photo, $chat_id = null, $caption = null, $reply_to_message_id = null, $reply_markup = null) {
360
-        $res = $this->exec('sendPhoto', [
361
-            'chat_id' => $this->getChatId($chat_id),
362
-            'photo' => $photo,
363
-            'caption' => $caption,
364
-            'reply_to_message_id' => $reply_to_message_id,
365
-            'reply_markup' => $reply_markup
366
-        ]);
367
-
368
-        return $res;
369
-    }
370
-
371
-    /**
372
-     * @param $video video file path
373
-     * @param null $chat_id
374
-     * @param null $reply_to_message_id
375
-     * @param null $reply_markup
376
-     */
377
-    public function sendVideo($video, $chat_id = null, $reply_to_message_id = null, $reply_markup = null) {
378
-        $res = $this->exec('sendVideo', [
379
-            'chat_id' => $this->getChatId($chat_id),
380
-            'video' => $video,
381
-            'reply_to_message_id' => $reply_to_message_id,
382
-            'reply_markup' => $reply_markup
383
-        ]);
384
-
385
-        return $res;
386
-    }
387
-
388
-    /**
389
-     *
390
-     * @param $sticker
391
-     * @param null $chat_id
392
-     * @param null $reply_to_message_id
393
-     * @param null $reply_markup
394
-     */
395
-    public function sendSticker($sticker, $chat_id = null, $reply_to_message_id = null, $reply_markup = null) {
396
-        $res = $this->exec('sendSticker', [
397
-            'chat_id' => $this->getChatId($chat_id),
398
-            'sticker' => $sticker,
399
-            'reply_to_message_id' => $reply_to_message_id,
400
-            'reply_markup' => $reply_markup
401
-        ]);
402
-
403
-        return $res;
404
-        // as soons as possible
405
-    }
406
-
407
-    /**
408
-     * @param $latitude
409
-     * @param $longitude
410
-     * @param null $chat_id
411
-     * @param null $reply_to_message_id
412
-     * @param null $reply_markup
413
-     */
414
-    public function sendLocation($latitude, $longitude, $chat_id = null, $reply_to_message_id = null, $reply_markup = null) {
415
-        $res = $this->exec('sendLocation', [
416
-            'chat_id' => $this->getChatId($chat_id),
417
-            'latitude' => $latitude,
418
-            'longitude' => $longitude,
419
-            'reply_to_message_id' => $reply_to_message_id,
420
-            'reply_markup' => $reply_markup
421
-        ]);
422
-
423
-        return $res;
424
-    }
425
-
426
-    /**
427
-     * @param $document
428
-     * @param null $chat_id
429
-     * @param null $reply_to_message_id
430
-     * @param null $reply_markup
431
-     */
432
-    public function sendDocument($document, $chat_id = null, $reply_to_message_id = null, $reply_markup = null) {
433
-        $res = $this->exec('sendDocument', [
434
-            'chat_id' => $this->getChatId($chat_id),
435
-            'document' => $document,
436
-            'reply_to_message_id' => $reply_to_message_id,
437
-            'reply_markup' => $reply_markup
438
-        ]);
439
-
440
-        return $res;
441
-    }
442
-
443
-    public function sendAudio($audio, $chat_id = null, $reply_to_message_id = null, $reply_markup = null) {
444
-        $res = $this->exec('sendAudio', [
445
-            'chat_id' => $this->getChatId($chat_id),
446
-            'audio' => $audio,
447
-            'reply_to_message_id' => $reply_to_message_id,
448
-            'reply_markup' => $reply_markup
449
-        ]);
450
-
451
-        return $res;
452
-    }
453
-
454
-    /**
455
-     * send chat action : Telegram::ACTION_TYPING , ...
456
-     * @param $action
457
-     * @param null $chat_id
458
-     */
459
-    public function sendChatAction($action, $chat_id = null) {
460
-        $res = $this->exec('sendChatAction', [
461
-            'chat_id' => $this->getChatId($chat_id),
462
-            'action' => $action
463
-        ]);
464
-
465
-        return $res;
466
-    }
467
-
468
-    /**
469
-     * @param $user_id
470
-     * @param null $offset
471
-     * @param null $limit
472
-     */
473
-    public function getUserProfilePhotos($user_id, $offset = null, $limit = null) {
474
-        $res = $this->exec('getUserProfilePhotos', [
475
-            'user_id' => $user_id,
476
-            'offset' => $offset,
477
-            'limit' => $limit
478
-        ]);
479
-
480
-        return $res;
481
-    }
482
-
483
-
484
-    public function answerInlineQuery($inline_query_id, $results, $cache_time = 0, $is_personal = false, $next_offset = '', $switch_pm_text = '', $switch_pm_parameter = '') {
485
-      $res = $this->exec('answerInlineQuery', [
486
-        'inline_query_id' => $inline_query_id,
487
-        'results' => json_encode($results),
488
-        'cache_time' => $cache_time,
489
-        'is_personal' => $is_personal,
490
-        'next_offset' => $next_offset,
491
-        'switch_pm_text' => $switch_pm_text,
492
-        'switch_pm_parameter' => $switch_pm_parameter
493
-      ]);
494
-
495
-      return $res;
496
-    }
497
-
498
-    /**
499
-     * @param $url
500
-     */
501
-    public function setWebhook($url) {
502
-        $res = $this->exec('setWebhook', [
503
-            'url' => $url
504
-        ]);
505
-
506
-        return $res;
507
-    }
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
+	 */
321
+	public function sendMessage($text, $chat_id = null, $disable_web_page_preview = false, $reply_to_message_id = null, $reply_markup = null) {
322
+		$this->sendChatAction(self::ACTION_TYPING, $chat_id);
323
+		return $this->exec('sendMessage', [
324
+			'chat_id' => $this->getChatId($chat_id),
325
+			'text' => $text,
326
+			'disable_web_page_preview' => $disable_web_page_preview,
327
+			'reply_to_message_id' => $reply_to_message_id,
328
+			'reply_markup' => $reply_markup
329
+		]);
330
+	}
331
+
332
+	/**
333
+	 * Get me
334
+	 */
335
+	public function getMe() {
336
+		return $this->exec('getMe');
337
+	}
338
+
339
+	/**
340
+	 * @param $from_id
341
+	 * @param $message_id
342
+	 * @param null $chat_id
343
+	 */
344
+	public function forwardMessage($from_id, $message_id, $chat_id = null) {
345
+		return $this->exec('forwardMessage', [
346
+			'chat_id' => $this->getChatId($chat_id),
347
+			'from_chat_id' => $from_id,
348
+			'message_id' => $message_id,
349
+		]);
350
+	}
351
+
352
+	/**
353
+	 * @param $photo photo file patch
354
+	 * @param null $chat_id
355
+	 * @param null $caption
356
+	 * @param null $reply_to_message_id
357
+	 * @param null $reply_markup
358
+	 */
359
+	public function sendPhoto($photo, $chat_id = null, $caption = null, $reply_to_message_id = null, $reply_markup = null) {
360
+		$res = $this->exec('sendPhoto', [
361
+			'chat_id' => $this->getChatId($chat_id),
362
+			'photo' => $photo,
363
+			'caption' => $caption,
364
+			'reply_to_message_id' => $reply_to_message_id,
365
+			'reply_markup' => $reply_markup
366
+		]);
367
+
368
+		return $res;
369
+	}
370
+
371
+	/**
372
+	 * @param $video video file path
373
+	 * @param null $chat_id
374
+	 * @param null $reply_to_message_id
375
+	 * @param null $reply_markup
376
+	 */
377
+	public function sendVideo($video, $chat_id = null, $reply_to_message_id = null, $reply_markup = null) {
378
+		$res = $this->exec('sendVideo', [
379
+			'chat_id' => $this->getChatId($chat_id),
380
+			'video' => $video,
381
+			'reply_to_message_id' => $reply_to_message_id,
382
+			'reply_markup' => $reply_markup
383
+		]);
384
+
385
+		return $res;
386
+	}
387
+
388
+	/**
389
+	 *
390
+	 * @param $sticker
391
+	 * @param null $chat_id
392
+	 * @param null $reply_to_message_id
393
+	 * @param null $reply_markup
394
+	 */
395
+	public function sendSticker($sticker, $chat_id = null, $reply_to_message_id = null, $reply_markup = null) {
396
+		$res = $this->exec('sendSticker', [
397
+			'chat_id' => $this->getChatId($chat_id),
398
+			'sticker' => $sticker,
399
+			'reply_to_message_id' => $reply_to_message_id,
400
+			'reply_markup' => $reply_markup
401
+		]);
402
+
403
+		return $res;
404
+		// as soons as possible
405
+	}
406
+
407
+	/**
408
+	 * @param $latitude
409
+	 * @param $longitude
410
+	 * @param null $chat_id
411
+	 * @param null $reply_to_message_id
412
+	 * @param null $reply_markup
413
+	 */
414
+	public function sendLocation($latitude, $longitude, $chat_id = null, $reply_to_message_id = null, $reply_markup = null) {
415
+		$res = $this->exec('sendLocation', [
416
+			'chat_id' => $this->getChatId($chat_id),
417
+			'latitude' => $latitude,
418
+			'longitude' => $longitude,
419
+			'reply_to_message_id' => $reply_to_message_id,
420
+			'reply_markup' => $reply_markup
421
+		]);
422
+
423
+		return $res;
424
+	}
425
+
426
+	/**
427
+	 * @param $document
428
+	 * @param null $chat_id
429
+	 * @param null $reply_to_message_id
430
+	 * @param null $reply_markup
431
+	 */
432
+	public function sendDocument($document, $chat_id = null, $reply_to_message_id = null, $reply_markup = null) {
433
+		$res = $this->exec('sendDocument', [
434
+			'chat_id' => $this->getChatId($chat_id),
435
+			'document' => $document,
436
+			'reply_to_message_id' => $reply_to_message_id,
437
+			'reply_markup' => $reply_markup
438
+		]);
439
+
440
+		return $res;
441
+	}
442
+
443
+	public function sendAudio($audio, $chat_id = null, $reply_to_message_id = null, $reply_markup = null) {
444
+		$res = $this->exec('sendAudio', [
445
+			'chat_id' => $this->getChatId($chat_id),
446
+			'audio' => $audio,
447
+			'reply_to_message_id' => $reply_to_message_id,
448
+			'reply_markup' => $reply_markup
449
+		]);
450
+
451
+		return $res;
452
+	}
453
+
454
+	/**
455
+	 * send chat action : Telegram::ACTION_TYPING , ...
456
+	 * @param $action
457
+	 * @param null $chat_id
458
+	 */
459
+	public function sendChatAction($action, $chat_id = null) {
460
+		$res = $this->exec('sendChatAction', [
461
+			'chat_id' => $this->getChatId($chat_id),
462
+			'action' => $action
463
+		]);
464
+
465
+		return $res;
466
+	}
467
+
468
+	/**
469
+	 * @param $user_id
470
+	 * @param null $offset
471
+	 * @param null $limit
472
+	 */
473
+	public function getUserProfilePhotos($user_id, $offset = null, $limit = null) {
474
+		$res = $this->exec('getUserProfilePhotos', [
475
+			'user_id' => $user_id,
476
+			'offset' => $offset,
477
+			'limit' => $limit
478
+		]);
479
+
480
+		return $res;
481
+	}
482
+
483
+
484
+	public function answerInlineQuery($inline_query_id, $results, $cache_time = 0, $is_personal = false, $next_offset = '', $switch_pm_text = '', $switch_pm_parameter = '') {
485
+	  $res = $this->exec('answerInlineQuery', [
486
+		'inline_query_id' => $inline_query_id,
487
+		'results' => json_encode($results),
488
+		'cache_time' => $cache_time,
489
+		'is_personal' => $is_personal,
490
+		'next_offset' => $next_offset,
491
+		'switch_pm_text' => $switch_pm_text,
492
+		'switch_pm_parameter' => $switch_pm_parameter
493
+	  ]);
494
+
495
+	  return $res;
496
+	}
497
+
498
+	/**
499
+	 * @param $url
500
+	 */
501
+	public function setWebhook($url) {
502
+		$res = $this->exec('setWebhook', [
503
+			'url' => $url
504
+		]);
505
+
506
+		return $res;
507
+	}
508 508
 
509 509
 }
Please login to merge, or discard this patch.