HOW TO - Receive Telegram message when partition storage is getting full

Tested on Debian 10

This guide relies on you having a TELEGRAM Messenger API and Chat or Channel ID for a telegram bot.

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:

test-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.

warning

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

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!

2 Likes

Nice one, thanks for sharing!
Will give it a try in a free minute…

1 Like

hi, you know there is option to set this up without touching a /etc or no cron - simpler…I guess you just google it up and share with your inputs - I suddenly do not recommend at all this setup.

Greetings unborn.

I’ve moved the /etc/telegram directory to '/home/scripts/telegram` modified the script and everything works fine from there on my machine,

Could the cron job be written better?

I can update the guide above if thats a better way to do this?

Cheers!

@happycoding yes, it can! BTW why even install telegram… all you need is to tell b0t to send message out to the client… got my point?

  • your code might seems nice but man there are more simplified examples…no need to even install or touch system, simple bash will send you notification when need it via telegram. All you need is to tell b0t something and it will send message… simple.
  • I cant take credit for the code. Its not mine :pray:

I’ve seen the short command line code to send a simple chat to a telegram bot.
But I like the idea of this plugin to add pictures and do other things. It seems pretty good so far.

If you fancy simplifying the process above (of receiving a notification on full disk space) via telegram. I’m sure it would be appreciated by the community, possibly more than pointing out there are simpler ways to do it :wink:

All the best

1 Like

Sure thing I can see it from the code you’ve provided, adding pictures and other things okay…its the way how you feel not how anyone other would feel… just reminder.

I do fancy simplifying the process described above… I do implement not only disk watcher space via telegram but also ssh logins, error logs plus some access logs for wp and other cmses. Right now I think this setup is a bit wrong - you do not install telegram on server.

Anyway knowledge does not come from google alone, but from years of testing and development so - how to put it in nice and simple manner?

…this setup you give to the community here in virtualmin is very old and not recommend - my one is same as anyone would do if they understand the program. I would not share this out widely yet as there is no one interesting except you , who seems to republish any knowledge within your name.

all the best,

The telegram API script is working well in a better directory, many thanks!
I will update accordingly the above this evening.

Look forward to other people improvements, that’s what community is about.

Best Wishes

UPDATED VERSION - File directory moved on install

These files are for sending (outgoing) messages via a telegram API on demand (executed by script) and will send with just these scripts below.
You dont need to install linux telegram desktop app.

Tested on Debian 10

This guide relies on you having a Telegram Messenger API and Chat or Channel ID for a telegram bot.

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

So here we go!

Two directories need to exist or be created (scripts + telegram):

Open Terminal:

mkdir -p /home/scripts/telegram

Now we need to create 3 files:

Create the first file

nano /home/scripts/telegram/telegram-notify

Then Paste:

#!/bin/bash
# ---------------------------------------------------
#  Send notification to a telegram account thru a bot account
#  Configuration is stored in /home/scripts/telegram/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="/home/scripts/telegram/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 /home/scripts/telegram/telegram-notify.conf

And paste:

# -------------------------------#
#   /home/scripts/telegram/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 script to call up when needed!

Before we add the script to monitor your storage area (by one off or regular polling in cron). Lets take a look at what the script 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 /home/scripts/telegram/telegram-notify --success --text "Action *sucessful* with markdown *bold* example"

And you should have received this message:

test-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
    . /home/scripts/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.

warning

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.
You could easily get the to run the script once an hour if needed.

Terminal:

crontab -e

And paste

0 22 * * * cd /home/scripts && ./storage-warning-telegram.sh >> /dev/null 2>&1

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!

See: http://www.bernaerts-nicolas.fr/linux/75-debian/351-debian-send-telegram-notification
For more commands for the script

*As ever, happy for improvements and constructive discussion :pray:

1 Like

Have changed the install directory on advice from a superior being…

So take a look down for the latest update :ok_hand:

Best Wishes!

@happycoding nice to see your improvements however regarding what program mean to do, why just not have one bash scrip…with telling user to run it manually or automatically via Cron. don’t get me wrong 8 years ago I was insufficient in writing programs and scripts which are essentially programs… I’ve learned a lot. anyway this is nice few steps solution for community here. of course I can provide one liner with only one command. That’s what people wants. well have nice day.

Morning!
It’s the script I have at this time and its only a pre formatted set of commands for the Telegram API. It really isn’t big!
It’s compiled and dead easy to change a Chat ID too in the separate config file.

The second calling/action script:

#!/bin/bash
CURRENT=$(df | grep '/dev/sda' | awk '{print $5}' | sed 's/%//g')
THRESHOLD=2

if [ "$CURRENT" -gt "$THRESHOLD" ] ; then
    . /home/scripts/telegram/telegram-notify --error --title "Storage Warning For Server1!" --text "Your /dev/sda partition available space is critically low. Used: $CURRENT%"
fi

Will be modified to check the status of other services and could be expanded to whatever needs.

Am really enjoying making progress.
I’m sure people in the community will improve on it in time.

Thanks, I do appreciate your your input/discussion on your method. However some code might be better, to keep this thread short :wink:

So… next step I’m looking at is to integrate some of these when they stop:

I’ve had BIND go down recently, after restoring a Webmin backup and knowing (within a chosen time) it had stopped would have been very useful!

Personally, currently I have CSF firewall installed which gives SSH login, IP bans, port scan attack notifications via email. So that’s down on my priority. But if someone else wants to add to the calling/action script to send these. I’m sure it would be useful to others.

A good one would be making CSF to call on the Telegram API script to send notifications!

I’m gonna crack on with the screenshot. Will keep the progress updated here for those interested :ok_hand:

Update

New install script incoming once I’ve fully tested it.

I’ve binned the telegram-notify script (for calling telegram API).
Messages now send in a two line command and I’ve managed to put all the icons into messages too (format of messages to be fine tuned).

sms

So monitoring the Virtualmin services (screenshot above in previous post) now works.

I’ve taken bits of code from here and there and modified them to work with the telegram command line API.

The new (much smaller) script watches system for failures and sends a notification when a process fails. It also tails logs and sends in the Message.

Am compiling an install.sh script to make installation really simple. Or you could just extract the scripts from that and mod accordingly!

The installer file will make the scripts run from systemd rather than cron…

Once I’ve checked this I’ll pop it online for others to have a play…

  • It will probably be another post. The description will be quite different than storage full warnings.

This could be incredibly useful (and perhaps a valid addition to) the scheduled monitoring of the ‘System and Server Status’ functionality of Webmin.

In fact, you can just use the existing Webmin functionality to run a command when a monitor goes down?

The scheduling is all handled already, so would just need to be able to run the script to ping off the notification to Telegram.

1 Like

@pixel_paul - It would be good to integrate something like that in the OS, yes!
Until then, for me, the new scripts have been good.

I’ve written the install script, works very well with optional choices. Still to upload onto GIt before sending a link.

Should be soon!

On install there are options:

  • You can choose folder install location.

  • It will install the Storage warning with an option of choosing how often you would like to poll this and at what % you want an alarm.

  • It will also do system services monitoring. You can pick which System services you would like to monitor and how often you would like to receive alerts.

Scripts are very small and there’s an uninstall script to remove or just uninstall to re-install with new options rather than edit the scripts.

Manually editing the scripts, you can change emoji on the messages etc…

I’ll hopefully have them on line for perusal soon!

I’m not referring to the O/S, but to existing Webmin functionality:

https://doxfer.webmin.com/Webmin/System_and_Server_Status

Perhaps this is something that can be added to Webmin as the current SMS notifications are obsolete for me (in the UK at least).

2 Likes

@pixel_paul i am already using telegram as solution to SMS or servers notifications and I think I would prefer to have it outside of virtualmin as it’s highly customisable and I’m not sure how would others receive option to only have notifications via telegram if they not using it.

guy here just touching the subject what you can have here however keep in mind he is following something found randomly on internet and modify by himself.

This topic was automatically closed 60 days after the last reply. New replies are no longer allowed.