Tested on Debian 10
This guide relies on you having a TELEGRAM Messenger API and Chat or Channel ID for a telegram bot.
- For directions on how to create bot >> https://sendpulse.com/knowledge-base/chatbot/create-telegram-chatbot
Disclaimer
I am not clever enough to have come up with this script. The original author is: http://www.bernaerts-nicolas.fr/linux/75-debian/351-debian-send-telegram-notification
But I noticed that some of his links were out of date/timing out so I’ve made this a beginner fool proof guide…
So here we go!
Three directories need to exist or be created:
Open Terminal:
mkdir /etc/telegram
mkdir /etc/telegram/conf
mkdir /home/scripts
Now we need to create 3 files:
Create the first file
nano /etc/telegram/telegram-notify
Then Paste:
#!/bin/bash
# ---------------------------------------------------
# Send notification to a telegram account thru a bot account
# Configuration is stored in /etc/telegram-notify.conf
# Depends on curl
#
# Revision history :
# 10/01/2016, V1.0 - Creation by N. Bernaerts
# 22/01/2016, V1.1 - Handle emoticons
# 06/08/2016, V1.2 - Add API key and User ID parameters
# Remove dependency to PERL
# 08/08/2016, V1.3 - Add --document, --html and --silent options
# 10/11/2016, V1.4 - Add --icon option
# 11/01/2018, V1.5 - Add possibility of piped text, idea from Yasir Atabani
# 19/05/2018, V1.6 - Add socks5 proxy option, idea from RangerRU
# 28/06/2018, V1.7 - Add --warning and --config options, idea from Markus Hof
# 08/08/2019, V1.8 - Add --file option (file holding text to display)
# 23/09/2019, V1.9 - Add --quiet option, thanks to Alberto Panu
# 06/02/2020, V2.0 - Add --disable_preview option, thanks to Alex P.
# ---------------------------------------------------
# initialise variables
NOTIFY_TEXT=""
DISPLAY_TEXT=""
DISPLAY_PICT=""
DISPLAY_ICON=""
DISPLAY_MODE="markdown"
DISABLE_PREVIEW="false"
DISPLAY_SILENT="false"
QUIET="false"
# Configuration file
FILE_CONF="/etc/telegram/conf/telegram-notify.conf"
# -------------------------------------------------------
# Check tools availability
# -------------------------------------------------------
command -v curl >/dev/null 2>&1 || { echo "[Error] Please install curl"; exit 1; }
# -------------------------------------------------------
# Loop to load arguments
# -------------------------------------------------------
# if no argument, display help
if [ $# -eq 0 ]
then
echo "Tool to send a message to a Telegram User or Channel."
echo "Message is sent from a Telegram Bot and can contain icon, text, image and/or document."
echo "Main parameters are :"
echo " --text <text> Text of the message (use - for piped text)"
echo " --file <file> File holding the text of the message"
echo " --photo <file> Image to display"
echo " --document <file> Document to transfer"
echo "Options are :"
echo " --title <title> Title of the message (if text message)"
echo " --html Use HTML mode for text content (markdown by default)"
echo " --disable_preview Don't create previews for links, image and/or document"
echo " --silent Send message in silent mode (no user notification on the client)"
echo " --quiet Don't print message to stdout"
echo " --config <file> use alternate config file, instead of default ${FILE_CONF}"
echo " --user <user-id> Recipient User or Channel ID (replaces user-id= in ${FILE_CONF})"
echo " --key <api-key> API Key of your Telegram bot (replaces api-key= in ${FILE_CONF})"
echo "Optional icons are :"
echo " --success Add a success icon"
echo " --warning Add a warning icon"
echo " --error Add an error icon"
echo " --question Add a question mark icon"
echo " --icon <code> Add an icon by UTF code (ex 1F355)"
echo "Here is an example of piped text :"
echo " echo 'text to be displayed' | telegram-notify --success --text -"
exit
fi
# loop to retrieve arguments
while test $# -gt 0
do
case "$1" in
"--text") shift; DISPLAY_TEXT="$1"; shift; ;;
"--file") shift; TEXTFILE="$1"; shift; ;;
"--photo") shift; PICTURE="$1"; shift; ;;
"--document") shift; DOCUMENT="$1"; shift; ;;
"--title") shift; DISPLAY_TITLE="$1"; shift; ;;
"--html") DISPLAY_MODE="html"; shift; ;;
"--disable_preview") DISABLE_PREVIEW="true"; shift; ;;
"--silent") DISPLAY_SILENT="true"; shift; ;;
"--quiet") QUIET="true"; shift; ;;
"--config") shift; FILE_CONF="$1"; shift; ;;
"--user") shift; USER_ID="$1"; shift; ;;
"--key") shift; API_KEY="$1"; shift; ;;
"--success") DISPLAY_ICON=$(echo -e "\U2705"); shift; ;;
"--warning") DISPLAY_ICON=$(echo -e "\U26A0"); shift; ;;
"--error") DISPLAY_ICON=$(echo -e "\U1F6A8"); shift; ;;
"--question") DISPLAY_ICON=$(echo -e "\U2753"); shift; ;;
"--icon") shift; DISPLAY_ICON=$(echo -e "\U$1"); shift; ;;
*) shift; ;;
esac
done
# -------------------------------------------------------
# Read configuration
# -------------------------------------------------------
# if configuration file is present
if [ -f "${FILE_CONF}" ]
then
# display used config file unless --quiet parameter is used
[ "${QUIET}" = "false" ] && echo "[Info] Using configuration file ${FILE_CONF}"
# if needed, load from configuration file
[ "${API_KEY}" = "" ] && API_KEY=$(cat "${FILE_CONF}" | grep "api-key=" | cut -d'=' -f2)
[ "${USER_ID}" = "" ] && USER_ID=$(cat "${FILE_CONF}" | grep "user-id=" | cut -d'=' -f2)
# load socks proxy from configuration file
SOCKS_PROXY=$(cat "${FILE_CONF}" | grep "socks-proxy=" | cut -d'=' -f2)
else
# display warning unless --quiet parameter is used
[ "${QUIET}" = "false" ] && echo "[Warning] Configuration file missing ${FILE_CONF}"
fi
# check API key and User ID
[ "${API_KEY}" = "" ] && { echo "[Error] Please provide API key or set it in ${FILE_CONF}"; exit 1; }
[ "${USER_ID}" = "" ] && { echo "[Error] Please provide User ID or set it in ${FILE_CONF}"; exit 1; }
# -------------------------------------------------------
# Check for file existence
# -------------------------------------------------------
# if text file, check for text file
[ "${TEXTFILE}" != "" -a ! -f "${TEXTFILE}" ] && { echo "[error] Text file ${TEXTFILE} doesn't exist"; exit 1; }
# if picture, check for image file
[ "${PICTURE}" != "" -a ! -f "${PICTURE}" ] && { echo "[error] Image file ${PICTURE} doesn't exist"; exit 1; }
# if document, check for document file
[ "${DOCUMENT}" != "" -a ! -f "${DOCUMENT}" ] && { echo "[error] Document file ${DOCUMENT} doesn't exist"; exit 1; }
# -------------------------------------------------------
# String preparation : space and line break
# -------------------------------------------------------
# if text is a file, get its content
[ -f "${TEXTFILE}" ] && DISPLAY_TEXT=$(cat "${TEXTFILE}")
# if text is to be read from pipe, get it
[ ! -t 0 -a "${DISPLAY_TEXT}" = "-" ] && DISPLAY_TEXT=$(cat)
# convert \n to LF
DISPLAY_TEXT=$(echo "${DISPLAY_TEXT}" | sed 's:\\n:\n:g')
# if icon defined, include ahead of notification
[ "${DISPLAY_ICON}" != "" ] && NOTIFY_TEXT="${DISPLAY_ICON} "
# if title defined, add it with line break
if [ "${DISPLAY_TITLE}" != "" ]
then
# convert title according to Markdown or HTML
[ "${DISPLAY_MODE}" = "html" ] && NOTIFY_TEXT="${NOTIFY_TEXT}<b>${DISPLAY_TITLE}</b>%0A%0A" \
|| NOTIFY_TEXT="${NOTIFY_TEXT}*${DISPLAY_TITLE}*%0A%0A"
fi
# if text defined, replace \n by HTML line break
[ "${DISPLAY_TEXT}" != "" ] && NOTIFY_TEXT="${NOTIFY_TEXT}${DISPLAY_TEXT}"
# -------------------------------------------------------
# Notification
# -------------------------------------------------------
# default option
ARR_OPTIONS=( "--silent" "--insecure" )
# if needed, socks5 option
[ "${SOCKS_PROXY}" != "" ] && ARR_OPTIONS=( "${ARR_OPTIONS[@]}" "--socks5-hostname" "${SOCKS_PROXY}" )
# if photo defined, display it with icon and caption
if [ "${PICTURE}" != "" ]
then
# display image
CURL_RESULT=$(curl "${ARR_OPTIONS[@]}" --form chat_id=${USER_ID} --form disable_notification=${DISPLAY_SILENT} --form disable_web_page_preview=${DISABLE_PREVIEW} --form photo="@${PICTURE}" --form caption="${NOTIFY_TEXT}" "https://api.telegram.org/bot${API_KEY}/sendPhoto")
# if document defined, send it with icon and caption
elif [ "${DOCUMENT}" != "" ]
then
# transfer document
CURL_RESULT=$(curl "${ARR_OPTIONS[@]}" --form chat_id=${USER_ID} --form disable_notification=${DISPLAY_SILENT} --form disable_web_page_preview=${DISABLE_PREVIEW} --form document="@${DOCUMENT}" --form caption="${NOTIFY_TEXT}" "https://api.telegram.org/bot${API_KEY}/sendDocument")
# else, if text is defined, display it with icon and title
elif [ "${NOTIFY_TEXT}" != "" ]
then
# display text message
CURL_RESULT=$(curl "${ARR_OPTIONS[@]}" --data chat_id="${USER_ID}" --data "disable_notification=${DISPLAY_SILENT}" --data "disable_web_page_preview=${DISABLE_PREVIEW}" --data "parse_mode=${DISPLAY_MODE}" --data "text=${NOTIFY_TEXT}" "https://api.telegram.org/bot${API_KEY}/sendMessage")
# else, nothing, error
else
# display error message unless --quiet parameter is used
[ "${QUIET}" = "false" ] && echo "[Error] Nothing to notify"
exit 1
fi
# check curl request result
echo ${CURL_RESULT} | grep '"ok":true' > /dev/null || { echo ${CURL_RESULT}; exit 1; }
# end
exit 0
To save your new file
Press CTRL and X together
Then Y
Then ENTER
Create Second file:
nano /etc/telegram/conf/telegram-notify.conf
And paste:
# -------------------------------#
# /etc/telegram/conf/telegram-notify.conf #
# -------------------------------#
[general]
api-key=YourAPIKey
user-id=YourUserOrChannelID
[network]
socks-proxy=
- Remember to add your telegram chatbot API and Chat or Channel ID to the file above!
To save your new file
Press CTRL and X together
Then Y
Then ENTER
ONCE SAVED:
- Now this is a fully functional Telegram communication module!
Before we add the script to monitor your storage area. Lets take a look at what the module can do.
There are some examples on the authors blog:
telegram-notify --success --text "Action *sucessful* with markdown *bold* example"
telegram-notify --error --title "Error" --text "Error message with a title"
telegram-notify --question --title "File content display" --text "/tmp/log.txt"
telegram-notify --icon 1F355 --text "Message with custom icon 1F355 and embedded image" --photo "/tmp/icon.png"
telegram-notify --text "Result is available in the embedded document" --document "/tmp/result.log"
So try this in terminal:
bash /etc/telegram/telegram-notify --success --text "Action *sucessful* with markdown *bold* example"
And you should have received this message:
Now we can go ahead and install the script to check storage available/send Telegram alert.
- I installed this script at
/home/scripts
For testing purposes in this script I’ve set the threshold for warning really low (2%) so you can test the action in terminal. You will need to reset this to a higher desired maximum later.
Lets make the script in Terminal:
nano /home/scripts/storage-warning-telegram.sh
Paste:
#!/bin/bash
CURRENT=$(df | grep '/dev/sda' | awk '{print $5}' | sed 's/%//g')
THRESHOLD=2
if [ "$CURRENT" -gt "$THRESHOLD" ] ; then
. /etc/telegram/telegram-notify --error --title "Storage Warning For Server1!" --text "Your /dev/sda partition available space is critically low. Used: $CURRENT%"
fi
And save the file…
- FYI: You will need to modify this script to suite your needs. My storage area is
/dev/sda
.
To find your /dev/ storage:
Terminal
lsblk -l
Once the file is edited. We are good to give the script a test!
We will need to change permissions for the file we just made…
chmod +x /home/scripts/storage-warning-telegram.sh
Then do a test run!
bash /home/scripts/storage-warning-telegram.sh
Voilla. Hopefully there’s your warning via TELEGRAM MESSENGER.
Now we will test a Cronjob to check the job executes.
This cron will send a message once a minute and will need to be altered once you know cronjob works.
Terminal:
crontab -e
Then paste:
* * * * * cd /home/scripts && ./storage-warning-telegram.sh >> /dev/null 2>&1
- Go make a cup of tea and you should receive a message in telegram shortly!
Once you know it works lets make a sensible cronjob…
This cronjob below will run at 22:00 daily.
Terminal:
crontab -e
And paste
0 22 * * * cd /home/scripts && ./storage-warning-telegram.sh >> /dev/null 2>&1
- To choose another cronjob time here’s a good link that explains cron times: https://crontab.guru/
Now you’ll need to go back to edit your warning script THRESHOLD to something a bit higher than 2%.
Terminal
nano /home/scripts/storage-warning-telegram.sh
Change the THRESHOLD=2
to whatever you like (I use 90) and save.
That should be good to go.
Enjoy
If anyone can improve on the use of this telegram-notify module with another fun bit of script or point out any errors in the post, let me know!