问题
on EC2
I have a crontab like that
* * * * * /usr/bin/php /opt/bitnami/apache2/htdocs/bot.php
The bot.php file
1 <?php
2
3 exec( 'touch /opt/bitnami/apache2/htdocs/testCron.txt');
4
5 $botToken="xxxxxxxxxxxxx";
6
7 $website="https://api.telegram.org/bot".$botToken;
8 $chatId=123456;
9 $params=[
10 'chat_id'=>$chatId,
11 'text'=>'test bitnami',
12 ];
13 $ch = curl_init($website . '/sendMessage');
14 curl_setopt($ch, CURLOPT_HEADER, false);
15 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
16 curl_setopt($ch, CURLOPT_POST, 1);
17 curl_setopt($ch, CURLOPT_POSTFIELDS, ($params));
18 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
19 $result = curl_exec($ch);
20
21 if ($result === FALSE) {
22 echo 'An error has occured: ' . curl_error($ch) . PHP_EOL;
23 }
24 else {
25 echo $result;
26 }
27
28 curl_close($ch);
29
30 ?>
testCron.txt is created so the cronTab works.
When I open bot.php with firefox the API call works and the bot sent the message on Telegram, but the PHP script with curl doesn't work with Cron.
I put htdocs and bot.php permissions to 777 for testing and it didn't work.
Any idea?
回答1:
Hint: I'm adding it as an answer since my reputation (as of now) is below 50.
As of now I would need more information in order to support. There might be multiple potential issues here. Let's see if we can go down the road together.
1. Make errors visible during cron execution
In this case you could check your logs inside your cron. I would suggest to log any output into a file by the this to your cron >> /var/log/my-cron.log 2>&1
.
* * * * * /usr/bin/php /opt/bitnami/apache2/htdocs/bot.php >> /opt/bitnami/apache2/htdocs/testCron.log 2>&1
From here on we can check if there is any execution errors, permission errors or some misconfiguration.
2. Check your error-log configuration
It might be that your errors are not displayed. Here is a good starting point for some configuration
// tells your script to report any error
error_reporting(E_ALL);
// tells your script to enable error logging and the location where it should log to
ini_set('log_errors', '1'); // tells your script to enable logging
ini_set('error_log', '/dev/stderr');
Let's see if this is enough to get an initial idea or if we need to dig deeper.
来源:https://stackoverflow.com/questions/60250579/telegram-bot-with-cron-and-php-script