Skip to content

Commit baec8e3

Browse files
authored
Merge pull request #19 from noplanman/cron
Cron
2 parents da9458f + 9ed9e51 commit baec8e3

File tree

8 files changed

+101
-17
lines changed

8 files changed

+101
-17
lines changed

CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ 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+
- Execute commands via cron, using `cron` action and `g` parameter.
78
### Changed
89
- Remodelled the config array to a more flexible structure.
910
### Deprecated

README.md

Lines changed: 37 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -40,18 +40,20 @@ and then run `composer update`
4040

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

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

4545
| Parameter | Description |
4646
| --------- | ----------- |
4747
| s | **s**ecret: This is a special secret value defined in the main `manager.php` file. |
4848
| | This parameter is required to call the script via browser! |
49-
| a | **a**ction: The actual action to perform. (handle (default), set, unset, reset) |
50-
| | **handle** executes the `getUpdates` method; **set** / **unset** / **reset** the Webhook. |
49+
| a | **a**ction: The actual action to perform. (handle (default), cron, set, unset, reset) |
50+
| | **handle** executes the `getUpdates` method; **cron** executes cron commands; **set** / **unset** / **reset** the webhook. |
5151
| l | **l**oop: Number of seconds to loop the script for (used for getUpdates method). |
5252
| | This would be used mainly via CLI, to continually get updates for a certain period. |
53-
| i | **i**nterval: Number of seconds to wait between getUpdates requests (used for getUpdates method, default: 2). |
53+
| i | **i**nterval: Number of seconds to wait between getUpdates requests (used for getUpdates method, default is 2). |
5454
| | This would be used mainly via CLI, to continually get updates for a certain period, every **i** seconds. |
55+
| g | **g**roup: Commands group for cron (only used together with `cron` action, default group is `default`). |
56+
| | Define which group of commands to execute via cron. Can be a comma separated list of groups. |
5557

5658
#### via browser
5759

@@ -74,6 +76,12 @@ Handle updates once:
7476
Handle updates for 30 seconds, fetching every 5 seconds:
7577
- `http://example.com/manager.php?s=super_secret&l=30&i=5`
7678

79+
**cron**
80+
81+
Execute commands via cron:
82+
- `http://example.com/manager.php?s=super_secret&a=cron&g=maintenance` or multiple groups
83+
- `http://example.com/manager.php?s=super_secret&a=cron&g=maintenance,cleanup`
84+
7785
#### via CLI
7886

7987
When using CLI, the secret is not necessary (since it could just be read from the file itself).
@@ -97,12 +105,18 @@ Handle updates once:
97105
Handle updates for 30 seconds, fetching every 5 seconds:
98106
- `$ php manager.php l=30 i=5`
99107

108+
**cron**
109+
110+
Execute commands via cron:
111+
- `$ php manager.php a=cron g=maintenance` or multiple groups
112+
- `$ php manager.php a=cron g=maintenance,cleanup`
113+
100114
### Create the manager PHP file
101115

102116
You can name this file whatever you like, it just has to be somewhere inside your PHP project (preferably in the root folder to make things easier).
103117
(Let's assume our file is called `manager.php`)
104118

105-
Let's start off with a simple example that uses the Webhook method:
119+
Let's start off with a simple example that uses the webhook method:
106120
```php
107121
<?php
108122

@@ -256,6 +270,24 @@ $bot = new BotManager([
256270
],
257271
],
258272

273+
// (array) All options that have to do with cron.
274+
'cron' => [
275+
// (array) List of groups that contain the commands to execute.
276+
'groups' => [
277+
// Each group has a name and array of commands.
278+
// When no group is defined, the default group gets executed.
279+
'default' => [
280+
'/default_cron_command',
281+
],
282+
'maintenance' => [
283+
'/db_cleanup',
284+
'/db_repair',
285+
'/log_rotate',
286+
'/message_admins Maintenance completed',
287+
],
288+
],
289+
],
290+
259291
// (string) Override the custom input of your bot (mostly for testing purposes!).
260292
'custom_input' => '{"some":"raw", "json":"update"}',
261293
]);

src/Action.php

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@ class Action
2222
'unset',
2323
'reset',
2424
'handle',
25+
'cron',
2526
];
2627

2728
/**

src/BotManager.php

Lines changed: 27 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -123,12 +123,18 @@ public function run(): self
123123
// Make sure this is a valid call.
124124
$this->validateSecret();
125125

126+
if (!$this->isValidRequest()) {
127+
throw new InvalidAccessException('Invalid access');
128+
}
129+
126130
if ($this->action->isAction(['set', 'unset', 'reset'])) {
127131
$this->validateAndSetWebhook();
128132
} elseif ($this->action->isAction('handle')) {
129-
// Set any extras.
130133
$this->setBotExtras();
131134
$this->handleRequest();
135+
} elseif ($this->action->isAction('cron')) {
136+
$this->setBotExtras();
137+
$this->handleCron();
132138
}
133139

134140
return $this;
@@ -337,6 +343,25 @@ public function handleRequest(): self
337343
return $this;
338344
}
339345

346+
/**
347+
* Handle cron.
348+
*
349+
* @return \NPM\TelegramBotManager\BotManager
350+
* @throws \Longman\TelegramBot\Exception\TelegramException
351+
*/
352+
public function handleCron(): self
353+
{
354+
$groups = explode(',', $this->params->getScriptParam('g', 'default'));
355+
356+
$commands = [];
357+
foreach ($groups as $group) {
358+
$commands = array_merge($commands, $this->params->getBotParam('cron.groups.' . $group, []));
359+
}
360+
$this->telegram->runCommands($commands);
361+
362+
return $this;
363+
}
364+
340365
/**
341366
* Get the number of seconds the script should loop.
342367
*
@@ -456,10 +481,6 @@ public function handleGetUpdates(): self
456481
*/
457482
public function handleWebhook(): self
458483
{
459-
if (!$this->isValidRequest()) {
460-
throw new InvalidAccessException('Invalid access');
461-
}
462-
463484
$this->telegram->handle();
464485

465486
return $this;
@@ -487,6 +508,7 @@ public function getOutput(): string
487508
*/
488509
public function isValidRequest(): bool
489510
{
511+
// If we're running from CLI, requests are always valid, unless we're running the tests.
490512
if ((!self::inTest() && 'cli' === PHP_SAPI) || false === $this->params->getBotParam('validate_request')) {
491513
return true;
492514
}

src/Params.php

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -18,10 +18,11 @@ class Params
1818
* @var array List of valid script parameters.
1919
*/
2020
private static $valid_script_params = [
21-
's',
22-
'a',
23-
'l',
24-
'i',
21+
's', // secret
22+
'a', // action
23+
'l', // loop
24+
'i', // interval
25+
'g', // group (for cron)
2526
];
2627

2728
/**
@@ -47,8 +48,8 @@ class Params
4748
'paths',
4849
'commands',
4950
'botan',
50-
'custom_input',
5151
'cron',
52+
'custom_input',
5253
];
5354

5455
/**

tests/TelegramBotManager/Tests/ActionTest.php

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@ public function testConstruct()
2020
self::assertEquals('unset', (new Action('unset'))->getAction());
2121
self::assertEquals('reset', (new Action('reset'))->getAction());
2222
self::assertEquals('handle', (new Action('handle'))->getAction());
23+
self::assertEquals('cron', (new Action('cron'))->getAction());
2324
}
2425

2526
/**

tests/TelegramBotManager/Tests/BotManagerTest.php

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,14 @@ public static function setUpBeforeClass()
4444
];
4545
}
4646

47+
/**
48+
* To test the live commands, act as if we're being called by Telegram.
49+
*/
50+
protected function makeRequestValid()
51+
{
52+
$_SERVER['REMOTE_ADDR'] = '149.154.167.197';
53+
}
54+
4755
public function testSetParameters()
4856
{
4957
$botManager = new BotManager(array_merge(ParamsTest::$demo_vital_params, [
@@ -239,9 +247,11 @@ public function testValidateAndSetWebhookSuccessLiveBot()
239247

240248
/**
241249
* @group live
250+
* @runInSeparateProcess
242251
*/
243252
public function testDeleteWebhookViaRunLiveBot()
244253
{
254+
$this->makeRequestValid();
245255
$_GET = ['a' => 'unset'];
246256
$botManager = new BotManager(array_merge(self::$live_params, [
247257
'webhook' => ['url' => 'https://example.com/hook.php'],
@@ -438,20 +448,24 @@ public function testIsValidRequestValidate()
438448

439449
/**
440450
* @group live
451+
* @runInSeparateProcess
441452
*/
442453
public function testGetUpdatesLiveBot()
443454
{
455+
$this->makeRequestValid();
444456
$botManager = new BotManager(self::$live_params);
445457
$output = $botManager->run()->getOutput();
446458
self::assertContains('Updates processed: 0', $output);
447459
}
448460

449461
/**
450462
* @group live
463+
* @runInSeparateProcess
451464
*/
452465
public function testGetUpdatesLoopLiveBot()
453466
{
454-
// Webhook must NOT be set for this to work!
467+
$this->makeRequestValid();
468+
// Webhook MUST NOT be set for this to work!
455469
$this->testDeleteWebhookViaRunLiveBot();
456470

457471
// Looping for 5 seconds should be enough to get a result.

tests/TelegramBotManager/Tests/ParamsTest.php

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -63,7 +63,19 @@ class ParamsTest extends \PHPUnit\Framework\TestCase
6363
'botan' => [
6464
'token' => 'botan_12345',
6565
],
66-
'custom_input' => '{"some":"raw", "json":"update"}',
66+
'cron' => [
67+
'groups' => [
68+
'default' => [
69+
'/default_cron_command',
70+
],
71+
'maintenance' => [
72+
'/db_cleanup',
73+
'/db_repair',
74+
'/log_rotate',
75+
],
76+
],
77+
],
78+
'custom_input' => '{"some":"raw", "json":"update"}',
6779
];
6880

6981
public function setUp()

0 commit comments

Comments
 (0)