問題描述
將我的 .php 輸出發送到 curl 命令,該命令使用機器人在電報上向我發送消息 (Send my .php output to a curl command that messages me on telegram using a bot)
我每隔幾分鐘就會執行一次以下 cron:
*/8 * * * * /usr/local/bin/php ‑f /home/xxx/yyyy.php >> /home/xxx/zzzz.log
目前它的輸出存儲在 .log
文件中。但我希望能夠通過電報機器人將輸出作為消息發送給我。
我已經製作了一個機器人並擁有 api 密鑰,但我不確定如何連接它們。
在電報api文檔上,它說我可以使用curl讓機器人通過在bash文件中執行以下操作向我發送消息:
#!/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
顯然在>>之後添加curl不起作用。這將如何完成?
參考解法
方法 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.
方法 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)
(by Patoshi パトシ、Itz Wam、Barmar)