-
-
Notifications
You must be signed in to change notification settings - Fork 954
Running with cron (scheduled commands)
Leonid74 edited this page Jul 30, 2020
·
3 revisions
Sometimes you want the bot to do some stuff in the background: maintenance, error reports, database cleanup...
Let's say we have a command that sends logs (if they exist) and a command that cleans up the database from records older than the number given as a parameter.
NOTE: This page assumes usage of Linux's cron.
- Copy example cron.php to a place of your choosing
- Make sure vendor path is correct
- Set basic configuration - just like in other hook/getUpdates scripts (
API KEY, BOT USERNAME, MYSQL connection details...
) - Set any other options (
Download/Upload paths, command configs
) here as well (Note: Botan.io integration is forced off!) - Set the commands you want to run -
$commands = ['/sendlogs', '/cleanup 30'];
- Add cron entry -
*/1 * * * * cd /home/user/bot/; /usr/local/bin/php -q cron.php > logs/cron.log 2>&1
(will print out output tologs/cron.log
, you can change this to path of your chosing)
- '
sendlogs
' without any parameters - '
cleanup
' with parameter '30
'
--
In commands made to be run by admin and a cron if you want the script to show output in the console (for cron.log
) you should consider having something like this at the bottom of the command (assumes $data['text']
hold the output):
prior version 0.45.0:
if ($message->getFrom()->getUsername() != $this->getTelegram()->getBotName()) {
return Request::sendMessage($data);
} else {
echo $data['text'] . PHP_EOL;
return Request::emptyResponse();
}
0.45.0 and above:
if ($message->getFrom()->getUsername() != $this->getTelegram()->getBotUsername()) {
return Request::sendMessage($data);
} else {
echo $data['text'] . PHP_EOL;
return Request::emptyResponse();
}
This will:
- allow the command to be run by user/admin and return output as a message (for example - running on demand database cleanup by admin and show number of affected rows)
- show command output in the console if run from cron (which will be written to
cron.log
) and don't send the message to the bot itself (which will return an error from Telegram API, bot cannot send message to itself)
- When using Webhook you can check if your command is run by cron by using
defined('STDIN')
check, this constant is only defined when script is run from CLI (will returnfalse
on the webspace - requests from Telegram API)!
Just like for other commands - $text = trim($message->getText(true));
$commands = ['your text message that triggers something', '/cleanup 30];