From 50d1706a067383ad68cd0b227b7b5b339f1157cb Mon Sep 17 00:00:00 2001 From: Christian Hesse Date: Wed, 2 Jun 2021 22:53:43 +0200 Subject: global-functions: make Telegram notifications a module --- global-config | 5 +- global-config-overlay | 2 +- global-config.changes | 2 + global-functions | 158 +----------------------------- global-functions.d/notification-telegram | 162 +++++++++++++++++++++++++++++++ 5 files changed, 169 insertions(+), 160 deletions(-) create mode 100644 global-functions.d/notification-telegram diff --git a/global-config b/global-config index 19d1215..d2b1f94 100644 --- a/global-config +++ b/global-config @@ -8,7 +8,7 @@ # Make sure all configuration properties are up to date and this # value is in sync with value in script 'global-functions'! -:global GlobalConfigVersion 53; +:global GlobalConfigVersion 54; # This is used for DNS and backup file. :global Domain "example.com"; @@ -25,7 +25,8 @@ #:global EmailGeneralCc "another@example.com,third@example.com"; # You can send Telegram notifications. Register a bot -# and add the token and chat ids here. +# and add the token and chat ids here, then install the module: +# $ScriptInstallUpdate global-functions.d/notification-telegram :global TelegramTokenId ""; :global TelegramChatId ""; #:global TelegramTokenId "123456:ABCDEF-GHI"; diff --git a/global-config-overlay b/global-config-overlay index 1cbaedf..1466a4d 100644 --- a/global-config-overlay +++ b/global-config-overlay @@ -8,7 +8,7 @@ # Make sure all configuration properties are up to date and this # value is in sync with value in script 'global-functions'! # Comment or remove to disable news and change notifications. -:global GlobalConfigVersion 53; +:global GlobalConfigVersion 54; # Copy configuration from global-config here and modify it. diff --git a/global-config.changes b/global-config.changes index 21d4941..1721ab0 100644 --- a/global-config.changes +++ b/global-config.changes @@ -57,6 +57,7 @@ 51="Added 'ipsec-to-dns' to add DNS records for IPSec peers from mode-config."; 52="Updated Let's Encrypt trust chain to use root certificate 'ISRG Root X1'. Do not re-import the old chain!"; 53="Added support to send notifications via Matrix."; + 54="Support for Telegram notifications moved to a module. It is installed automatically if required."; }; # Migration steps to be applied on script updates @@ -64,4 +65,5 @@ 41=":global SendNotification; \$SendNotification (\"Migration mechanism\") (\"Congratulations!\nSuccessfully tested the new migration mechanism.\");"; 47="/ certificate remove [ find where fingerprint=\"731d3d9cfaa061487a1d71445a42f67df0afca2a6c2d2f98ff7b3ce112b1f568\" or fingerprint=\"25847d668eb4f04fdd40b12b6b0740c567da7d024308eb6c2c96fe41d9de218d\" ];"; 52=":global CertificateDownload; :if ([ :len [ / certificate find where fingerprint=\"67add1166b020ae61b8f5fc96813c04c2aa589960796865572a3c7e737613dfd\" or fingerprint=\"96bcec06264976f37460779acf28c5a7cfe8a3c0aae11a8ffcee05c0bddf08c6\" ] ] < 2) do={ \$CertificateDownload \"R3\"; }; / certificate remove [ find where fingerprint=\"0687260331a72403d909f105e69bcf0d32e1bd2493ffc6d9206d11bcd6770739\" ];"; + 54=":global ScriptInstallUpdate; :global TelegramTokenId; :global TelegramChatId; :if ([ :len \$TelegramTokenId ] > 0 && [ :len \$TelegramChatId ] > 0) do={ \$ScriptInstallUpdate global-functions.d/notification-telegram; }"; }; diff --git a/global-functions b/global-functions index b3db3dd..02afd8f 100644 --- a/global-functions +++ b/global-functions @@ -8,7 +8,7 @@ # https://git.eworm.de/cgit/routeros-scripts/about/ # expected configuration version -:global ExpectedConfigVersion 53; +:global ExpectedConfigVersion 54; # global variables not to be changed by user :global GlobalFunctionsReady false; @@ -27,7 +27,6 @@ :global EitherOr; :global EscapeForRegEx; :global FlushEmailQueue; -:global FlushTelegramQueue; :global GetMacVendor; :global GetRandom20CharHex; :global GetRandomNumber; @@ -48,8 +47,6 @@ :global SendEMail2; :global SendNotification; :global SendNotification2; -:global SendTelegram; -:global SendTelegram2; :global SymbolByUnicodeName; :global SymbolForNotification; :global TimeIsSync; @@ -373,42 +370,6 @@ } } -# flush telegram queue -:set FlushTelegramQueue do={ - :global TelegramQueue; - - :global LogPrintExit2; - - :local AllDone true; - :local QueueLen [ :len $TelegramQueue ]; - - :if ([ :len [ / system scheduler find where name="FlushTelegramQueue" ] ] > 0 && $QueueLen = 0) do={ - $LogPrintExit2 warning $0 ("Flushing Telegram messages from scheduler, but queue is empty.") false; - } - - :foreach Id,Message in=$TelegramQueue do={ - :if ([ :typeof $Message ] = "array" ) do={ - :do { - / tool fetch check-certificate=yes-without-crl output=none http-method=post \ - ("https://api.telegram.org/bot" . ($Message->"tokenid") . "/sendMessage") \ - http-data=("chat_id=" . ($Message->"chatid") . \ - "&disable_notification=" . ($Message->"silent") . \ - "&disable_web_page_preview=true&parse_mode=" . ($Message->"parsemode") . \ - "&text=" . ($Message->"text")) as-value; - :set ($TelegramQueue->$Id); - } on-error={ - $LogPrintExit2 debug $0 ("Sending queued Telegram message failed.") false; - :set AllDone false; - } - } - } - - :if ($AllDone = true && $QueueLen = [ :len $TelegramQueue ]) do={ - / system scheduler remove [ find where name="FlushTelegramQueue" ]; - :set TelegramQueue; - } -} - # get MAC vendor :set GetMacVendor do={ :local Mac [ :tostr $1 ]; @@ -621,107 +582,6 @@ } } -# send notification via telegram - expects one array argument -:set ($NotificationFunctions->"telegram") do={ - :local Notification $1; - - :global Identity; - :global TelegramChatId; - :global TelegramChatIdOverride; - :global TelegramFixedWidthFont; - :global TelegramQueue; - :global TelegramTokenId; - :global TelegramTokenIdOverride; - - :global CertificateAvailable; - :global CharacterReplace; - :global EitherOr; - :global IfThenElse; - :global LogPrintExit2; - :global SymbolForNotification; - :global UrlEncode; - - :local EscapeMD do={ - :global TelegramFixedWidthFont; - - :global CharacterReplace; - :global IfThenElse; - - :if ($TelegramFixedWidthFont != true) do={ - :return ($1 . [ $IfThenElse ($2 = "body") "\n" "" ]); - } - - :local Return $1; - :local Chars { - "body"={ "\\"; "`" }; - "hint"={ "_"; "*"; "["; "]"; "("; ")"; "~"; "`"; ">"; - "#"; "+"; "-"; "="; "|"; "{"; "}"; "."; "!" }; - } - :foreach Char in=($Chars->$2) do={ - :set Return [ $CharacterReplace $Return $Char ("\\" . $Char) ]; - } - - :if ($2 = "body") do={ - :return ("```\n" . $Return . "\n```"); - } - - :return $Return; - } - - :local ChatId [ $EitherOr ($TelegramChatIdOverride->($Notification->"origin")) $TelegramChatId ]; - :local TokenId [ $EitherOr ($TelegramTokenIdOverride->($Notification->"origin")) $TelegramTokenId ]; - - :if ([ :len $TokenId ] = 0 || [ :len $ChatId ] = 0) do={ - :return false; - } - - :local Truncated false; - :local LenLink [ :len ($Notification->"link") ]; - :local Text ("[" . $Identity . "] " . ($Notification->"subject") . "\n\n" . ($Notification->"message")); - :local LenText [ :len $Text ]; - :if ($LenText > (3968 - $LenLink)) do={ - :set Text [ $EscapeMD ([ :pick $Text 0 (3840 - $LenLink) ] . "...") "body" ]; - :set Truncated true; - } else={ - :set Text [ $EscapeMD $Text "body" ]; - } - :if ($LenLink > 0) do={ - :set Text ($Text . "\n" . [ $SymbolForNotification "link" ] . [ $EscapeMD ($Notification->"link") "hint" ]); - } - :if ($Truncated = true) do={ - :set Text ($Text . "\n" . [ $SymbolForNotification "scissors" ] . \ - [ $EscapeMD ("The Telegram message was too long and has been truncated, cut off " . \ - (($LenText - [ :len $Text ]) * 100 / $LenText) . "%!") "hint" ]); - } - :set Text [ $UrlEncode $Text ]; - :local ParseMode [ $IfThenElse ($TelegramFixedWidthFont = true) "MarkdownV2" "" ]; - - :do { - :if ([ $CertificateAvailable "Go Daddy Secure Certificate Authority - G2" ] = false) do={ - $LogPrintExit2 warning $0 ("Downloading required certificate failed.") true; - } - / tool fetch check-certificate=yes-without-crl output=none http-method=post \ - ("https://api.telegram.org/bot" . $TokenId . "/sendMessage") \ - http-data=("chat_id=" . $ChatId . "&disable_notification=" . ($Notification->"silent") . \ - "&disable_web_page_preview=true&parse_mode=" . $ParseMode . "&text=" . $Text) as-value; - } on-error={ - $LogPrintExit2 info $0 ("Failed sending telegram notification! Queuing...") false; - - :if ([ :typeof $TelegramQueue ] = "nothing") do={ - :set TelegramQueue [ :toarray "" ]; - } - :set Text ($Text . [ $UrlEncode ("\n" . [ $SymbolForNotification "alarm-clock" ] . \ - [ $EscapeMD ("This message was queued since " . [ / system clock get date ] . \ - " " . [ / system clock get time ] . " and may be obsolete.") "hint" ]) ]); - :set ($TelegramQueue->[ :len $TelegramQueue ]) { chatid=$ChatId; tokenid=$TokenId; - parsemode=$ParseMode; text=$Text; silent=($Notification->"silent") }; - :if ([ :len [ / system scheduler find where name="FlushTelegramQueue" ] ] = 0) do={ - / system scheduler add name=FlushTelegramQueue interval=1m start-time=startup \ - on-event=":global FlushTelegramQueue; \$FlushTelegramQueue;"; - } - } -} - # parse key value store :set ParseKeyValueStore do={ :local Source $1; @@ -1074,22 +934,6 @@ } } -# send notification via telegram - expects at lease two string arguments -:set SendTelegram do={ - :global SendTelegram2; - - $SendTelegram2 ({ subject=$1; message=$2; link=$3; silent=$4 }); -} - -# send notification via telegram - expects one array argument -:set SendTelegram2 do={ - :local Notification $1; - - :global NotificationFunctions; - - ($NotificationFunctions->"telegram") ("\$NotificationFunctions->\"telegram\"") $Notification; -} - # return UTF-8 symbol for unicode name :set SymbolByUnicodeName do={ :local Symbols { diff --git a/global-functions.d/notification-telegram b/global-functions.d/notification-telegram new file mode 100644 index 0000000..1509a2e --- /dev/null +++ b/global-functions.d/notification-telegram @@ -0,0 +1,162 @@ +#!rsc by RouterOS +# RouterOS script: global-functions.d/notification-telegram +# Copyright (c) 2013-2021 Christian Hesse +# https://git.eworm.de/cgit/routeros-scripts/about/COPYING.md + +:global FlushTelegramQueue; +:global NotificationFunctions; +:global SendTelegram; +:global SendTelegram2; + +# flush telegram queue +:set FlushTelegramQueue do={ + :global TelegramQueue; + + :global LogPrintExit2; + + :local AllDone true; + :local QueueLen [ :len $TelegramQueue ]; + + :if ([ :len [ / system scheduler find where name="FlushTelegramQueue" ] ] > 0 && $QueueLen = 0) do={ + $LogPrintExit2 warning $0 ("Flushing Telegram messages from scheduler, but queue is empty.") false; + } + + :foreach Id,Message in=$TelegramQueue do={ + :if ([ :typeof $Message ] = "array" ) do={ + :do { + / tool fetch check-certificate=yes-without-crl output=none http-method=post \ + ("https://api.telegram.org/bot" . ($Message->"tokenid") . "/sendMessage") \ + http-data=("chat_id=" . ($Message->"chatid") . \ + "&disable_notification=" . ($Message->"silent") . \ + "&disable_web_page_preview=true&parse_mode=" . ($Message->"parsemode") . \ + "&text=" . ($Message->"text")) as-value; + :set ($TelegramQueue->$Id); + } on-error={ + $LogPrintExit2 debug $0 ("Sending queued Telegram message failed.") false; + :set AllDone false; + } + } + } + + :if ($AllDone = true && $QueueLen = [ :len $TelegramQueue ]) do={ + / system scheduler remove [ find where name="FlushTelegramQueue" ]; + :set TelegramQueue; + } +} + +# send notification via telegram - expects one array argument +:set ($NotificationFunctions->"telegram") do={ + :local Notification $1; + + :global Identity; + :global TelegramChatId; + :global TelegramChatIdOverride; + :global TelegramFixedWidthFont; + :global TelegramQueue; + :global TelegramTokenId; + :global TelegramTokenIdOverride; + + :global CertificateAvailable; + :global CharacterReplace; + :global EitherOr; + :global IfThenElse; + :global LogPrintExit2; + :global SymbolForNotification; + :global UrlEncode; + + :local EscapeMD do={ + :global TelegramFixedWidthFont; + + :global CharacterReplace; + :global IfThenElse; + + :if ($TelegramFixedWidthFont != true) do={ + :return ($1 . [ $IfThenElse ($2 = "body") "\n" "" ]); + } + + :local Return $1; + :local Chars { + "body"={ "\\"; "`" }; + "hint"={ "_"; "*"; "["; "]"; "("; ")"; "~"; "`"; ">"; + "#"; "+"; "-"; "="; "|"; "{"; "}"; "."; "!" }; + } + :foreach Char in=($Chars->$2) do={ + :set Return [ $CharacterReplace $Return $Char ("\\" . $Char) ]; + } + + :if ($2 = "body") do={ + :return ("```\n" . $Return . "\n```"); + } + + :return $Return; + } + + :local ChatId [ $EitherOr ($TelegramChatIdOverride->($Notification->"origin")) $TelegramChatId ]; + :local TokenId [ $EitherOr ($TelegramTokenIdOverride->($Notification->"origin")) $TelegramTokenId ]; + + :if ([ :len $TokenId ] = 0 || [ :len $ChatId ] = 0) do={ + :return false; + } + + :local Truncated false; + :local LenLink [ :len ($Notification->"link") ]; + :local Text ("[" . $Identity . "] " . ($Notification->"subject") . "\n\n" . ($Notification->"message")); + :local LenText [ :len $Text ]; + :if ($LenText > (3968 - $LenLink)) do={ + :set Text [ $EscapeMD ([ :pick $Text 0 (3840 - $LenLink) ] . "...") "body" ]; + :set Truncated true; + } else={ + :set Text [ $EscapeMD $Text "body" ]; + } + :if ($LenLink > 0) do={ + :set Text ($Text . "\n" . [ $SymbolForNotification "link" ] . [ $EscapeMD ($Notification->"link") "hint" ]); + } + :if ($Truncated = true) do={ + :set Text ($Text . "\n" . [ $SymbolForNotification "scissors" ] . \ + [ $EscapeMD ("The Telegram message was too long and has been truncated, cut off " . \ + (($LenText - [ :len $Text ]) * 100 / $LenText) . "%!") "hint" ]); + } + :set Text [ $UrlEncode $Text ]; + :local ParseMode [ $IfThenElse ($TelegramFixedWidthFont = true) "MarkdownV2" "" ]; + + :do { + :if ([ $CertificateAvailable "Go Daddy Secure Certificate Authority - G2" ] = false) do={ + $LogPrintExit2 warning $0 ("Downloading required certificate failed.") true; + } + / tool fetch check-certificate=yes-without-crl output=none http-method=post \ + ("https://api.telegram.org/bot" . $TokenId . "/sendMessage") \ + http-data=("chat_id=" . $ChatId . "&disable_notification=" . ($Notification->"silent") . \ + "&disable_web_page_preview=true&parse_mode=" . $ParseMode . "&text=" . $Text) as-value; + } on-error={ + $LogPrintExit2 info $0 ("Failed sending telegram notification! Queuing...") false; + + :if ([ :typeof $TelegramQueue ] = "nothing") do={ + :set TelegramQueue [ :toarray "" ]; + } + :set Text ($Text . [ $UrlEncode ("\n" . [ $SymbolForNotification "alarm-clock" ] . \ + [ $EscapeMD ("This message was queued since " . [ / system clock get date ] . \ + " " . [ / system clock get time ] . " and may be obsolete.") "hint" ]) ]); + :set ($TelegramQueue->[ :len $TelegramQueue ]) { chatid=$ChatId; tokenid=$TokenId; + parsemode=$ParseMode; text=$Text; silent=($Notification->"silent") }; + :if ([ :len [ / system scheduler find where name="FlushTelegramQueue" ] ] = 0) do={ + / system scheduler add name=FlushTelegramQueue interval=1m start-time=startup \ + on-event=":global FlushTelegramQueue; \$FlushTelegramQueue;"; + } + } +} + +# send notification via telegram - expects at lease two string arguments +:set SendTelegram do={ + :global SendTelegram2; + + $SendTelegram2 ({ subject=$1; message=$2; link=$3; silent=$4 }); +} + +# send notification via telegram - expects one array argument +:set SendTelegram2 do={ + :local Notification $1; + + :global NotificationFunctions; + + ($NotificationFunctions->"telegram") ("\$NotificationFunctions->\"telegram\"") $Notification; +} -- cgit v1.2.3-54-g00ecf