skip to Main Content

I have the following cron executed every few minutes:

*/8 * * * * /usr/local/bin/php -f /home/xxx/yyyy.php >> /home/xxx/zzzz.log

Currently its output is being stored in the .log file. But I want to be able to send the output to me as messages via a telegram bot.

I made a bot already and have the api keys, but I’m unsure how to connect them.

On the telegram api docs, it says I can use curl to have the bot send me a message by doing the following in a bash file:

#!/bin/bash

CHATID="1234"
KEY="abcd"
TIME="10"
URL="https://api.telegram.org/bot$KEY/sendMessage"
TEXT="Hello world"

curl -s --max-time $TIME -d "chat_id=$CHATID&disable_web_page_preview=1&text=$TEXT" $URL >/dev/null

adding curl after >> obviously doesn’t work. How would this be done?

2

Answers


  1. You can redirect your cron output to a script, or a command by using a pipe (|)
    here is an example :

    */8 * * * * /usr/local/bin/php -f /home/xxx/yyyy.php | tee /home/xxx/zzzz.log | /home/xxx/telegram.sh
    
    

    This will write the output of your command to /home/xxx/zzzz.log and send it to the stdin of the script.

    Login or Signup to reply.
  2. Assign the output of the PHP script to the TEXT shell variable

    CHATID="1234"
    KEY="abcd"
    TIME="10"
    URL="https://api.telegram.org/bot$KEY/sendMessage"
    TEXT=$(usr/local/bin/php -f /home/xxx/yyyy.php)
    # URL-encode some special characters
    TEXT=${TEXT//%/%25}
    TEXT=${TEXT//&/%26}
    TEXT=${TEXT//=/%3D}
    TEXT=${TEXT// /%20}
    curl -s --max-time $TIME -d "chat_id=$CHATID&disable_web_page_preview=1&text=$TEXT" "$URL" >/dev/null
    

    Put the above in a shell script and run that from cron instead of running the PHP script directly.

    If you also want it sent to the log file, you can use the tee command:

    TEXT=$(usr/local/bin/php -f /home/xxx/yyyy.php | tee -a /home/xxx/zzzz.log)
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search