I want to monitor server logs using telegram bot api with this script:
#!/bin/bash
CHATID="id"
KEY="key"
TIME="10"
URL="https://api.telegram.org/bot$KEY/sendMessage"
TEXT=$(tee)
curl -s --max-time $TIME -d "chat_id=$CHATID&disable_web_page_preview=1&text=$TEXT" $URL >/dev/null
Then pipe logs output to the script by using:
tail -f /var/log/my.log | ./telegram_log.sh
But it doesn't send the output.
your script remains stuck at the line
TEXT=$(tee)
because tee
it's waiting for stdin
to be closed, but it will never happen, because tail -f
keeps it open to "follow" the file.
to send a message on each new log line you should process each incoming line and not waiting for the whole stdin
. a simple while read
should do it, for example:
$ more bot.sh
#!/bin/sh
while IFS= read -r line; do
echo send new line as msg: "$line"
# TODO here goes curl etc...
done
$ touch log
$ tail -f log | ./bot.sh
send new line as msg: hello
send new line as msg: world
send new line as msg: goodbye
and on another terminal i did:
$ echo hello >> log
$ echo world >> log
$ echo goodbye >> log
$