|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace PhpBotFramework\Commands; |
|
4
|
|
|
|
|
5
|
|
|
use PhpBotFramework\Entities\CallbackQuery; |
|
6
|
|
|
|
|
7
|
|
|
trait CallbackCommand { |
|
8
|
|
|
|
|
9
|
|
|
/** |
|
10
|
|
|
* \addtogroup Commands |
|
11
|
|
|
* @{ |
|
12
|
|
|
*/ |
|
13
|
|
|
|
|
14
|
|
|
/** \brief Store the command triggered on callback query. */ |
|
15
|
|
|
protected $_callback_commands; |
|
16
|
|
|
|
|
17
|
|
|
/** |
|
18
|
|
|
* \brief Add a function that will be executed everytime a callback query contains a string as data |
|
19
|
|
|
* \details Use this syntax: |
|
20
|
|
|
* |
|
21
|
|
|
* addMessageCommand("menu", function($bot, $callback_query) { |
|
22
|
|
|
* $bot->editMessageText($callback_query['message']['message_id'], "This is the menu"); }); |
|
23
|
|
|
* @param $data The string that will trigger this function. |
|
24
|
|
|
* @param $script The function that will be triggered by the callback query if it contains the $data string. Must take an object(the bot) and an array(the callback query received). |
|
25
|
|
|
*/ |
|
26
|
|
|
public function addCallbackCommand(string $data, callable $script) { |
|
27
|
|
|
|
|
28
|
|
|
$this->_callback_commands[] = [ |
|
29
|
|
|
'data' => $data, |
|
30
|
|
|
'script' => $script, |
|
31
|
|
|
]; |
|
32
|
|
|
|
|
33
|
|
|
} |
|
34
|
|
|
|
|
35
|
|
|
/** |
|
36
|
|
|
* \brief (<i>Internal</i>) Process the callback query and check if it triggers a command of this type. |
|
37
|
|
|
* @param $callback_query Callback query to process. |
|
38
|
|
|
* @return True if the callback query triggered a command. |
|
39
|
|
|
*/ |
|
40
|
|
|
protected function processCallbackCommand(array $callback_query) : bool { |
|
41
|
|
|
|
|
42
|
|
|
// Check for callback commands |
|
43
|
|
|
if (isset($callback_query['data'])) { |
|
44
|
|
|
|
|
45
|
|
|
// Iterate over all commands |
|
46
|
|
|
foreach ($this->_callback_commands as $trigger) { |
|
47
|
|
|
|
|
48
|
|
|
// If command is found in callback data |
|
49
|
|
|
if (strpos($trigger['data'], $callback_query['data']) !== false) { |
|
50
|
|
|
|
|
51
|
|
|
$this->_chat_id = $callback_query['message']['chat']['id']; |
|
|
|
|
|
|
52
|
|
|
|
|
53
|
|
|
// Trigger the script |
|
54
|
|
|
$trigger['script']($this, new CallbackQuery($callback_query)); |
|
55
|
|
|
|
|
56
|
|
|
// The callback triggered a command, return true |
|
57
|
|
|
return true; |
|
58
|
|
|
} |
|
59
|
|
|
|
|
60
|
|
|
} |
|
61
|
|
|
|
|
62
|
|
|
} |
|
63
|
|
|
|
|
64
|
|
|
return false; |
|
65
|
|
|
|
|
66
|
|
|
} |
|
67
|
|
|
|
|
68
|
|
|
/** @} */ |
|
69
|
|
|
|
|
70
|
|
|
} |
|
71
|
|
|
|
In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:
Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion: