Skip to content

Commit da9458f

Browse files
authored
Merge pull request #18 from noplanman/improved_setup
Redesign config setup array and add array-dot notation for retrieving…
2 parents 09e93c6 + 6cd9240 commit da9458f

File tree

6 files changed

+272
-118
lines changed

6 files changed

+272
-118
lines changed

CHANGELOG.md

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,12 @@ The format is based on [Keep a Changelog](http://keepachangelog.com/) and this p
44
## [Unreleased]
55
### Added
66
- Ability to define custom valid IPs to access webhook.
7+
### Changed
8+
- Remodelled the config array to a more flexible structure.
9+
### Deprecated
10+
### Removed
11+
### Fixed
12+
### Security
713

814
## [0.43.0] - 2017-04-17
915
### Added

README.md

Lines changed: 116 additions & 43 deletions
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,7 @@ and then run `composer update`
4040

4141
What use would this library be if you couldn't perform any actions?!
4242

43-
There are 3 parameters available to get things rolling:
43+
There are 4 parameters available to get things rolling:
4444

4545
| Parameter | Description |
4646
| --------- | ----------- |
@@ -109,7 +109,7 @@ Let's start off with a simple example that uses the Webhook method:
109109
use NPM\TelegramBotManager\BotManager;
110110

111111
// Load composer.
112-
require __DIR__ . '/vendor/autoload.php';
112+
require_once __DIR__ . '/vendor/autoload.php';
113113

114114
try {
115115
$bot = new BotManager([
@@ -119,7 +119,9 @@ try {
119119
'secret' => 'super_secret',
120120

121121
// Extras.
122-
'webhook' => 'https://example.com/manager.php',
122+
'webhook' => [
123+
'url' => 'https://example.com/manager.php',
124+
]
123125
]);
124126
$bot->run();
125127
} catch (\Exception $e) {
@@ -130,11 +132,21 @@ try {
130132
### Set vital bot parameters
131133

132134
The vital parameters are:
133-
- Bot API key
134-
- Bot username
135-
- A secret
136135

137-
What secret you ask? Well, this is a user-defined key that is required to execute any of the library features.
136+
```php
137+
$bot = new BotManager([
138+
// (string) Bot API key provided by @BotFather.
139+
'api_key' => '12345:my_api_key',
140+
// (string) Bot username that was defined when creating the bot.
141+
'bot_username' => 'my_own_bot',
142+
// (string) A secret password required to authorise access to the webhook.
143+
'secret' => 'super_secret',
144+
145+
...
146+
]);
147+
```
148+
149+
The `secret` is a user-defined key that is required to execute any of the library's features.
138150
Best make it long, random and very unique!
139151

140152
For 84 random characters:
@@ -151,42 +163,103 @@ Enable admins? Add custom command paths? Set up logging?
151163

152164
**All no problem!**
153165

154-
Here is a list of available extra parameters:
155-
156-
| Parameter | Description |
157-
| --------- | ----------- |
158-
| validate_request | Only allow webhook access from valid Telegram API IPs. |
159-
| *bool* | *default is `true`* |
160-
| valid_ips | When using `validate_request`, also allow these IPs (single, CIDR, wildcard, range). |
161-
| *array* | *e.g.* `['1.2.3.4', '192.168.1.0/24', '10/8', '5.6.*', '1.1.1.1-2.2.2.2']` |
162-
| webhook | URL to the manager PHP file used for setting up the Webhook. |
163-
| *string* | *e.g.* `'https://example.com/manager.php'` |
164-
| certificate | Path to a self-signed certificate (if necessary). |
165-
| *string* | *e.g.* `__DIR__ . '/server.crt'` |
166-
| max_connections | Maximum allowed simultaneous HTTPS connections to the webhook. |
167-
| *int* | *e.g.* `20` |
168-
| allowed_updates | List the types of updates you want your bot to receive. |
169-
| *array* | *e.g.* `['message', 'edited_channel_post', 'callback_query']` |
170-
| logging | Path(s) where to the log files should be put. This is an array that can contain all 3 log file paths (`error`, `debug` and `update`). |
171-
| *array* | *e.g.* `['error' => __DIR__ . '/php-telegram-bot-error.log']` |
172-
| limiter | Enable or disable the limiter functionality, also accepts options array. |
173-
| *bool|array* | *e.g.* `true` or `false` or `['interval' => 2]` |
174-
| admins | An array of user ids that have admin access to your bot. |
175-
| *array* | *e.g.* `[12345]` |
176-
| mysql | Mysql credentials to connect a database (necessary for [`getUpdates`](#using-getupdates-method) method!). |
177-
| *array* | *e.g.* `['host' => '127.0.0.1', 'user' => 'root', 'password' => 'root', 'database' => 'telegram_bot']` |
178-
| download_path | Custom download path. |
179-
| *string* | *e.g.* `__DIR__ . '/Download'` |
180-
| upload_path | Custom upload path. |
181-
| *string* | *e.g.* `__DIR__ . '/Upload'` |
182-
| commands_paths | A list of custom commands paths. |
183-
| *array* | *e.g.* `[__DIR__ . '/CustomCommands']` |
184-
| command_configs | A list of all custom command configs. |
185-
| *array* | *e.g.* `['sendtochannel' => ['your_channel' => '@my_channel']` |
186-
| botan_token | The Botan.io token to be used for analytics. |
187-
| *string* | *e.g.* `'botan_12345'` |
188-
| custom_input | Override the custom input of your bot (mostly for testing purposes!). |
189-
| *string* | *e.g.* `'{"some":"raw", "json":"update"}'` |
166+
Here is a complete list of all available extra parameters:
167+
168+
```php
169+
$bot = new BotManager([
170+
...
171+
172+
// (array) All options that have to do with the webhook.
173+
'webhook' => [
174+
// (string) URL to the manager PHP file used for setting up the webhook.
175+
'url' => 'https://example.com/manager.php',
176+
// (string) Path to a self-signed certificate (if necessary).
177+
'certificate' => __DIR__ . '/server.crt',
178+
// (int) Maximum allowed simultaneous HTTPS connections to the webhook.
179+
'max_connections' => 20,
180+
// (array) List the types of updates you want your bot to receive.
181+
'allowed_updates' => ['message', 'edited_channel_post', 'callback_query'],
182+
],
183+
184+
// (bool) Only allow webhook access from valid Telegram API IPs.
185+
'validate_request' => true,
186+
// (array) When using `validate_request`, also allow these IPs.
187+
'valid_ips' => [
188+
'1.2.3.4', // single
189+
'192.168.1.0/24', // CIDR
190+
'10/8', // CIDR (short)
191+
'5.6.*', // wildcard
192+
'1.1.1.1-2.2.2.2', // range
193+
],
194+
195+
// (array) Paths where the log files should be put.
196+
'logging' => [
197+
// (string) Log file for all incoming update requests.
198+
'update' => __DIR__ . '/php-telegram-bot-update.log',
199+
// (string) Log file for debug purposes.
200+
'debug' => __DIR__ . '/php-telegram-bot-debug.log',
201+
// (string) Log file for all errors.
202+
'error' => __DIR__ . '/php-telegram-bot-error.log',
203+
],
204+
205+
// (array) All options that have to do with the limiter.
206+
'limiter' => [
207+
// (bool) Enable or disable the limiter functionality.
208+
'enabled' => true,
209+
// (array) Any extra options to pass to the limiter.
210+
'options' => [
211+
// (float) Interval between request handles.
212+
'interval' => 0.5,
213+
],
214+
],
215+
216+
// (array) An array of user ids that have admin access to your bot (must be integers).
217+
'admins' => [12345],
218+
219+
// (array) Mysql credentials to connect a database (necessary for [`getUpdates`](#using-getupdates-method) method!).
220+
'mysql' => [
221+
'host' => '127.0.0.1',
222+
'user' => 'root',
223+
'password' => 'root',
224+
'database' => 'telegram_bot',
225+
],
226+
227+
// (array) List of configurable paths.
228+
'paths' => [
229+
// (string) Custom download path.
230+
'download' => __DIR__ . '/Download',
231+
// (string) Custom upload path.
232+
'upload' => __DIR__ . '/Upload',
233+
],
234+
235+
// (array) All options that have to do with commands.
236+
'commands' => [
237+
// (array) A list of custom commands paths.
238+
'paths' => [
239+
__DIR__ . '/CustomCommands',
240+
],
241+
// (array) A list of all custom command configs.
242+
'configs' => [
243+
'sendtochannel' => ['your_channel' => '@my_channel'],
244+
'weather' => ['owm_api_key' => 'owm_api_key_12345'],
245+
],
246+
],
247+
248+
// (array) All options that have to do with botan.
249+
'botan' => [
250+
// (string) The Botan.io token to be used for analytics.
251+
'token' => 'botan_12345',
252+
// (array) Any extra options to pass to botan.
253+
'options' => [
254+
// (float) Custom timeout for requests.
255+
'timeout' => 3,
256+
],
257+
],
258+
259+
// (string) Override the custom input of your bot (mostly for testing purposes!).
260+
'custom_input' => '{"some":"raw", "json":"update"}',
261+
]);
262+
```
190263

191264
### Using getUpdates method
192265

src/BotManager.php

Lines changed: 53 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -187,7 +187,7 @@ public function validateSecret(bool $force = false): self
187187
public function validateAndSetWebhook(): self
188188
{
189189
$webhook = $this->params->getBotParam('webhook');
190-
if (empty($webhook) && $this->action->isAction(['set', 'reset'])) {
190+
if (empty($webhook['url'] ?? null) && $this->action->isAction(['set', 'reset'])) {
191191
throw new InvalidWebhookException('Invalid webhook');
192192
}
193193

@@ -199,14 +199,14 @@ public function validateAndSetWebhook(): self
199199

200200
if ($this->action->isAction(['set', 'reset'])) {
201201
$webhook_params = array_filter([
202-
'certificate' => $this->params->getBotParam('certificate'),
203-
'max_connections' => $this->params->getBotParam('max_connections'),
204-
'allowed_updates' => $this->params->getBotParam('allowed_updates'),
202+
'certificate' => $webhook['certificate'] ?? null,
203+
'max_connections' => $webhook['max_connections'] ?? null,
204+
'allowed_updates' => $webhook['allowed_updates'] ?? null,
205205
]);
206206

207207
$this->handleOutput(
208208
$this->telegram->setWebhook(
209-
$webhook . '?a=handle&s=' . $this->params->getBotParam('secret'),
209+
$webhook['url'] . '?a=handle&s=' . $this->params->getBotParam('secret'),
210210
$webhook_params
211211
)->getDescription() . PHP_EOL
212212
);
@@ -241,23 +241,59 @@ private function handleOutput(string $output): self
241241
*/
242242
public function setBotExtras(): self
243243
{
244-
$telegram_extras = [
244+
$this->setBotExtrasTelegram();
245+
$this->setBotExtrasRequest();
246+
247+
return $this;
248+
}
249+
250+
/**
251+
* Set extra bot parameters for Telegram object.
252+
*
253+
* @return \NPM\TelegramBotManager\BotManager
254+
* @throws \Longman\TelegramBot\Exception\TelegramException
255+
*/
256+
protected function setBotExtrasTelegram(): self
257+
{
258+
$simple_extras = [
245259
'admins' => 'enableAdmins',
246260
'mysql' => 'enableMySql',
247-
'botan_token' => 'enableBotan',
248-
'commands_paths' => 'addCommandsPaths',
261+
'commands.paths' => 'addCommandsPaths',
249262
'custom_input' => 'setCustomInput',
250-
'download_path' => 'setDownloadPath',
251-
'upload_path' => 'setUploadPath',
263+
'paths.download' => 'setDownloadPath',
264+
'paths.upload' => 'setUploadPath',
252265
];
253-
// For telegram extras, just pass the single param value to the Telegram method.
254-
foreach ($telegram_extras as $param_key => $method) {
266+
// For simple telegram extras, just pass the single param value to the Telegram method.
267+
foreach ($simple_extras as $param_key => $method) {
255268
$param = $this->params->getBotParam($param_key);
256269
if (null !== $param) {
257270
$this->telegram->$method($param);
258271
}
259272
}
260273

274+
// Custom command configs.
275+
$command_configs = $this->params->getBotParam('commands.configs', []);
276+
foreach ($command_configs as $command => $config) {
277+
$this->telegram->setCommandConfig($command, $config);
278+
}
279+
280+
// Botan with options.
281+
if ($botan_token = $this->params->getBotParam('botan.token')) {
282+
$botan_options = $this->params->getBotParam('botan.options', []);
283+
$this->telegram->enableBotan($botan_token, $botan_options);
284+
}
285+
286+
return $this;
287+
}
288+
289+
/**
290+
* Set extra bot parameters for Request class.
291+
*
292+
* @return \NPM\TelegramBotManager\BotManager
293+
* @throws \Longman\TelegramBot\Exception\TelegramException
294+
*/
295+
protected function setBotExtrasRequest(): self
296+
{
261297
$request_extras = [
262298
// None at the moment...
263299
];
@@ -270,19 +306,10 @@ public function setBotExtras(): self
270306
}
271307

272308
// Special cases.
273-
$limiter = $this->params->getBotParam('limiter', []);
274-
if (is_array($limiter)) {
275-
Request::setLimiter(true, $limiter);
276-
} else {
277-
Request::setLimiter($limiter);
278-
}
279-
280-
$command_configs = $this->params->getBotParam('command_configs');
281-
if (is_array($command_configs)) {
282-
/** @var array $command_configs */
283-
foreach ($command_configs as $command => $config) {
284-
$this->telegram->setCommandConfig($command, $config);
285-
}
309+
$limiter_enabled = $this->params->getBotParam('limiter.enabled');
310+
if ($limiter_enabled !== null) {
311+
$limiter_options = $this->params->getBotParam('limiter.options', []);
312+
Request::setLimiter($limiter_enabled, $limiter_options);
286313
}
287314

288315
return $this;
@@ -297,7 +324,7 @@ public function setBotExtras(): self
297324
*/
298325
public function handleRequest(): self
299326
{
300-
if (empty($this->params->getBotParam('webhook'))) {
327+
if (empty($this->params->getBotParam('webhook.url'))) {
301328
if ($loop_time = $this->getLoopTime()) {
302329
$this->handleGetUpdatesLoop($loop_time, $this->getLoopInterval());
303330
} else {

0 commit comments

Comments
 (0)