Home /  MMonit /  Telegram Notification

Telegram bot | M/Monit | Troubleshooting | Monit

M/Monit comes with a pre-defined Telegram Alert service which sends alerts to a Telegram group through a Telegram bot. You need a Telegram account. This guide takes about 10 minutes. See Alert Services for how Alert Services work in general.

1. Create a bot and a group

  1. In Telegram, open a chat with @BotFather (the verified one, with the blue check mark) and send /newbot. Choose a display name (e.g. M/Monit Alerts) and a username ending in bot.
  2. BotFather answers with the bot's token, e.g. 123456789:AAH.... Keep it secret: anyone with the token controls the bot.
  3. Create a group for the alerts (or use an existing one) and add the bot as a member.
  4. In the group, send /start@your_bot_username, so that the bot receives a message from the group.
  5. Open https://api.telegram.org/bot<token>/getUpdates in a browser, with your token in place of <token>. Find "chat":{"id": in the answer: this negative number is the group's chat id (supergroups start with -100).

If getUpdates returns an empty list, send another message in the group and reload the page.

2. Configure M/Monit

  1. In M/Monit go to Admin -> Alerts -> Alert Service and open the Telegram Alert row with the arrow on the right.
  2. URL/Endpoint: the chat id, including the minus sign. For a public channel, its @username works too; the bot must be an administrator of the channel.
  3. API Key/Token: the bot token.
  4. Press Test Service. A test alert appears in the group and M/Monit shows The script finished with exit status 0 with Telegram's answer, which starts with {"ok":true.
  5. Press Update.

Then use the service in an alert rule: on the Rules tab choose the action Execute Service and Telegram Alert, save the rule and switch it on. See Alert Services.

Troubleshooting

A Telegram message holds at most 4096 characters; since M/Monit 4.5.0 the service's Maximum Content Length is 3500 by default, so M/Monit shortens a longer event description and ends it with ....

When Telegram refuses a message, Test Service shows The script failed with exit status 1 with Telegram's answer; during a rule run the answer is written to logs/mmonit.log.

Telegram's answerMeaning
"error_code":401,"description":"Unauthorized"The bot token is wrong.
"error_code":400,"description":"Bad Request: chat not found"The chat id is wrong (check the minus sign), or the bot is not a member of the group.
"error_code":403,"description":"Forbidden: bot was kicked from the group chat"Add the bot to the group again.
"Bad Request: group chat was upgraded to a supergroup chat"The group became a supergroup and got a new id. Use the migrate_to_chat_id value from the answer as the chat id.

Monit

Without M/Monit, Monit can run the same script with exec. Save it as, for instance, /usr/local/etc/monit/telegram-alert.sh, fill in the chat id and the token at the top and make it readable only for the user that runs Monit (chmod 700):

Note: Monit has no Maximum Content Length: the script sends the event description whole, so Telegram refuses an alert whose description is longer than the 4096 characters of a message (the script then exits with 1).

#!/bin/sh
# M/Monit 4.5.0 "Telegram Alert" script, for Monit's exec
ENDPOINT="-1001234567890"          # group chat id
APIKEY="123456789:your-bot-token"  # bot token from @BotFather

# Monit passes the event values as they are; M/Monit escapes them for the message (HTML (& < >) and JSON): do the same here
_nl='
'
_replace() {
  _r= _t=$1
  while :; do
    case $_t in
      *"$2"*) _r=$_r${_t%%"$2"*}$3; _t=${_t#*"$2"} ;;
      *) break ;;
    esac
  done
  printf '%s' "$_r$_t"
}
_json_escape() {
  _s=$(printf '%s' "$1" | tr -d '\000-\010\013\014\016-\037')
  _s=$(_replace "$_s" '\' '\\')
  _s=$(_replace "$_s" '"' '\"')
  _s=$(_replace "$_s" "$_nl" '\n')
  _s=$(_replace "$_s" "$(printf '\r')" '\r')
  _replace "$_s" "$(printf '\t')" '\t'
}
_html() {
  _h=$(_replace "$1" '&' '&amp;')
  _h=$(_replace "$_h" '<' '&lt;')
  _replace "$_h" '>' '&gt;'
}
MONIT_HOST=$(_json_escape "$(_html "$MONIT_HOST")")
MONIT_SERVICE=$(_json_escape "$(_html "$MONIT_SERVICE")")
MONIT_DESCRIPTION=$(_json_escape "$(_html "$MONIT_DESCRIPTION")")

# Generate the Telegram message payload with HTML formatting
generate_payload() {
  printf '{
    "chat_id": "%s",
    "text": "<b>Alert from M/Monit</b>\\n\\n<pre>%s\\n\\nHost:    %s\\nService: %s\\nAction:  %s\\n\\nEvent:\\n%s\\n\\nDescription:\\n%s</pre>",
    "parse_mode": "HTML"
}' "$ENDPOINT" "$MONIT_DATE" "$MONIT_HOST" "$MONIT_SERVICE" "$MONIT_ACTION" "$MONIT_EVENT" "$MONIT_DESCRIPTION"
}

# Generate and send the payload
payload=$(generate_payload)
response=$(curl -sS -X POST \
     -H "Content-Type: application/json" \
     -d "$payload" \
     "https://api.telegram.org/bot$APIKEY/sendMessage") || exit
printf "%s\n" "$response"
case "$response" in
  *'"ok":true'*|*'"ok": true'*) ;;
  *) exit 1 ;;
esac

Then call it from any check in the Monit control file, for failure and recovery:

check host www.example.com with address www.example.com
    if failed port 443 protocol https
        then exec "/usr/local/etc/monit/telegram-alert.sh"
        else if succeeded then exec "/usr/local/etc/monit/telegram-alert.sh"