diff options
Diffstat (limited to 'telegram-chat.rsc')
-rw-r--r-- | telegram-chat.rsc | 265 |
1 files changed, 155 insertions, 110 deletions
diff --git a/telegram-chat.rsc b/telegram-chat.rsc index 62a6ccc..5db4860 100644 --- a/telegram-chat.rsc +++ b/telegram-chat.rsc @@ -1,150 +1,195 @@ #!rsc by RouterOS # RouterOS script: telegram-chat -# Copyright (c) 2023 Christian Hesse <mail@eworm.de> -# https://git.eworm.de/cgit/routeros-scripts/about/COPYING.md +# Copyright (c) 2023-2025 Christian Hesse <mail@eworm.de> +# https://rsc.eworm.de/COPYING.md +# +# requires RouterOS, version=7.15 +# requires device-mode, fetch # # use Telegram to chat with your Router and send commands -# https://git.eworm.de/cgit/routeros-scripts/about/doc/telegram-chat.md +# https://rsc.eworm.de/doc/telegram-chat.md -:local 0 "telegram-chat"; :global GlobalFunctionsReady; :while ($GlobalFunctionsReady != true) do={ :delay 500ms; } -:global Identity; -:global TelegramChatActive; -:global TelegramChatGroups; -:global TelegramChatId; -:global TelegramChatIdsTrusted; -:global TelegramChatOffset; -:global TelegramChatRunTime; -:global TelegramTokenId; +:local ExitOK false; +:do { + :local ScriptName [ :jobname ]; -:global CertificateAvailable; -:global EitherOr; -:global EscapeForRegEx; -:global GetRandom20CharAlNum; -:global IfThenElse; -:global LogPrintExit2; -:global MkDir; -:global ScriptLock; -:global SendTelegram2; -:global SymbolForNotification; -:global ValidateSyntax; -:global WaitForFile; -:global WaitFullyConnected; + :global Identity; + :global TelegramChatActive; + :global TelegramChatGroups; + :global TelegramChatId; + :global TelegramChatIdsTrusted; + :global TelegramChatOffset; + :global TelegramChatRunTime; + :global TelegramMessageIDs; + :global TelegramRandomDelay; + :global TelegramTokenId; -$ScriptLock $0; + :global CertificateAvailable; + :global EitherOr; + :global EscapeForRegEx; + :global GetRandom20CharAlNum; + :global IfThenElse; + :global LogPrint; + :global MAX; + :global MIN; + :global MkDir; + :global RandomDelay; + :global RmDir; + :global ScriptLock; + :global SendTelegram2; + :global SymbolForNotification; + :global ValidateSyntax; + :global WaitForFile; + :global WaitFullyConnected; -$WaitFullyConnected; + :if ([ $ScriptLock $ScriptName ] = false) do={ + :set ExitOK true; + :error false; + } -:if ([ :typeof $TelegramChatOffset ] != "array") do={ - :set TelegramChatOffset { 0; 0; 0 }; -} + $WaitFullyConnected; -:if ([ $CertificateAvailable "Go Daddy Secure Certificate Authority - G2" ] = false) do={ - $LogPrintExit2 warning $0 ("Downloading required certificate failed.") true; -} + :if ([ :typeof $TelegramChatOffset ] != "array") do={ + :set TelegramChatOffset { 0; 0; 0 }; + } + :if ([ :typeof $TelegramRandomDelay ] != "num") do={ + :set TelegramRandomDelay 0; + } -:local JsonGetKey do={ - :local Array [ :toarray $1 ]; - :local Key [ :tostr $2 ]; + :if ([ $CertificateAvailable "Go Daddy Root Certificate Authority - G2" ] = false) do={ + $LogPrint warning $ScriptName ("Downloading required certificate failed."); + :set ExitOK true; + :error false; + } - :for I from=0 to=([ :len $Array ] - 1) do={ - :if (($Array->$I) = $Key) do={ - :if ($Array->($I + 1) = ":") do={ - :return ($Array->($I + 2)); + $RandomDelay $TelegramRandomDelay; + + :local Data false; + :for I from=1 to=4 do={ + :if ($Data = false) do={ + :do { + :set Data ([ /tool/fetch check-certificate=yes-without-crl output=user \ + ("https://api.telegram.org/bot" . $TelegramTokenId . "/getUpdates?offset=" . \ + $TelegramChatOffset->0 . "&allowed_updates=%5B%22message%22%5D") as-value ]->"data"); + :set TelegramRandomDelay [ $MAX 0 ($TelegramRandomDelay - 1) ]; + } on-error={ + :if ($I < 4) do={ + $LogPrint debug $ScriptName ("Fetch failed, " . $I . ". try."); + :set TelegramRandomDelay [ $MIN 15 ($TelegramRandomDelay + 5) ]; + :delay (($I * $I) . "s"); + } } - :return [ :pick ($Array->($I + 1)) 1 [ :len ($Array->($I + 1)) ] ]; } } - :return false; -} + :if ($Data = false) do={ + $LogPrint warning $ScriptName ("Failed getting updates."); + :set ExitOK true; + :error false; + } -:local Data; -:do { - :set Data ([ /tool/fetch check-certificate=yes-without-crl output=user \ - ("https://api.telegram.org/bot" . $TelegramTokenId . "/getUpdates?offset=" . \ - $TelegramChatOffset->0 . "&allowed_updates=%5B%22message%22%5D") as-value ]->"data"); - :set Data [ :pick $Data ([ :find $Data "[" ] + 1) ([ :len $Data ] - 2) ]; -} on-error={ - $LogPrintExit2 debug $0 ("Failed getting updates from Telegram.") true; -} + :local JSON [ :deserialize from=json value=$Data ]; + :local UpdateID 0; + :local Uptime [ /system/resource/get uptime ]; + :foreach Update in=($JSON->"result") do={ + :set UpdateID ($Update->"update_id"); + :local Message ($Update->"message"); + :local IsReply ([ :typeof ($Message->"reply_to_message") ] = "string"); + :local IsMyReply ($TelegramMessageIDs->[ :tostr ($Message->"reply_to_message"->"message_id") ]); + :if (($IsMyReply = 1 || $TelegramChatOffset->0 > 0 || $Uptime > 5m) && $UpdateID >= $TelegramChatOffset->2) do={ + :local Trusted false; + :local Chat ($Message->"chat"); + :local From ($Message->"from"); + :local Command ($Message->"text"); + :local ThreadId [ $IfThenElse ($Message->"is_topic_message") ($Message->"message_thread_id") "" ]; -:local UpdateID 0; -:local Uptime [ /system/resource/get uptime ]; -:foreach Update in=[ :toarray $Data ] do={ - :set UpdateID [ $JsonGetKey $Update "update_id" ]; - :if (($TelegramChatOffset->0 > 0 || $Uptime > 5m) && $UpdateID >= $TelegramChatOffset->2) do={ - :local Trusted false; - :local Message [ $JsonGetKey $Update "message" ]; - :local MessageId [ $JsonGetKey $Message "message_id" ]; - :local From [ $JsonGetKey $Message "from" ]; - :local FromID [ $JsonGetKey $From "id" ]; - :local FromUserName [ $JsonGetKey $From "username" ]; - :local ChatID [ $JsonGetKey [ $JsonGetKey $Message "chat" ] "id" ]; - :local Text [ $JsonGetKey $Message "text" ]; - :foreach IdsTrusted in=($TelegramChatId, $TelegramChatIdsTrusted) do={ - :if ($FromID = $IdsTrusted || $FromUserName = $IdsTrusted) do={ - :set Trusted true; + :foreach IdsTrusted in=($TelegramChatId, $TelegramChatIdsTrusted) do={ + :if ($From->"id" = $IdsTrusted || $From->"username" = $IdsTrusted) do={ + :set Trusted true; + } } - } - :if ($Trusted = true) do={ - :if ([ :pick $Text 0 1 ] = "!") do={ - :if ($Text ~ ("^! *(" . [ $EscapeForRegEx $Identity ] . "|@" . $TelegramChatGroups . ")\$")) do={ - :set TelegramChatActive true; - } else={ - :set TelegramChatActive false; + :if ($Trusted = true) do={ + :local Done false; + :if ($Command = "?") do={ + $LogPrint info $ScriptName ("Sending notice for update " . $UpdateID . "."); + $SendTelegram2 ({ origin=$ScriptName; chatid=($Chat->"id"); silent=true; \ + replyto=($Message->"message_id"); threadid=$ThreadId; \ + subject=([ $SymbolForNotification "speech-balloon" ] . "Telegram Chat"); \ + message=([ $IfThenElse ([ :len ($From->"first_name") ] > 0) ("Hello " . ($From->"first_name") . "!\n\n") ] . \ + "Online" . [ $IfThenElse $TelegramChatActive " (and active!)" ] . ", awaiting your commands!") }); + :set Done true; } - $LogPrintExit2 info $0 ("Now " . [ $IfThenElse $TelegramChatActive "active" "passive" ] . \ - " from update " . $UpdateID . "!") false; - } else={ - :if ($TelegramChatActive = true && $Text != false && [ :len $Text ] > 0) do={ - :if ([ $ValidateSyntax $Text ] = true) do={ + :if ($Done = false && [ :pick $Command 0 1 ] = "!") do={ + :if ($Command ~ ("^! *(" . [ $EscapeForRegEx $Identity ] . "|@" . $TelegramChatGroups . ")\$")) do={ + :set TelegramChatActive true; + } else={ + :set TelegramChatActive false; + } + $LogPrint info $ScriptName ("Now " . [ $IfThenElse $TelegramChatActive "active" "passive" ] . \ + " from update " . $UpdateID . "!"); + :set Done true; + } + :if ($Done = false && ($IsMyReply = 1 || ($IsReply = false && \ + $TelegramChatActive = true)) && [ :len $Command ] > 0) do={ + :if ([ $ValidateSyntax $Command ] = true) do={ :local State ""; :local File ("tmpfs/telegram-chat/" . [ $GetRandom20CharAlNum 6 ]); - $MkDir "tmpfs/telegram-chat"; - $LogPrintExit2 info $0 ("Running command from update " . $UpdateID . ": " . $Text) false; - :execute script=(":do {\n" . $Text . "\n} on-error={ /file/add name=\"" . $File . ".failed\" };" . \ - "/file/add name=\"" . $File . ".done\"") file=$File; + :if ([ $MkDir "tmpfs/telegram-chat" ] = false) do={ + $LogPrint error $ScriptName ("Failed creating directory!"); + :set ExitOK true; + :error false; + } + $LogPrint info $ScriptName ("Running command from update " . $UpdateID . ": " . $Command); + :execute script=(":do {\n" . $Command . "\n} on-error={ /file/add name=\"" . $File . ".failed\" };" . \ + "/file/add name=\"" . $File . ".done\"") file=($File . "\00"); :if ([ $WaitForFile ($File . ".done") [ $EitherOr $TelegramChatRunTime 20s ] ] = false) do={ - :set State "The command did not finish, still running in background.\n\n"; + :set State ([ $SymbolForNotification "warning-sign" ] . "The command did not finish, still running in background.\n\n"); } :if ([ :len [ /file/find where name=($File . ".failed") ] ] > 0) do={ - :set State "The command failed with an error!\n\n"; + :set State ([ $SymbolForNotification "cross-mark" ] . "The command failed with an error!\n\n"); } - :local Content [ /file/get ($File . ".txt") contents ]; - $SendTelegram2 ({ origin=$0; chatid=$ChatID; silent=false; replyto=$MessageId; \ + :local Content ([ /file/read chunk-size=32768 file=$File as-value ]->"data"); + $SendTelegram2 ({ origin=$ScriptName; chatid=($Chat->"id"); silent=true; \ + replyto=($Message->"message_id"); threadid=$ThreadId; \ subject=([ $SymbolForNotification "speech-balloon" ] . "Telegram Chat"); \ - message=("Command:\n" . $Text . "\n\n" . $State . [ $IfThenElse ([ :len $Content ] > 0) \ - ("Output:\n" . $Content) [ $IfThenElse ([ /file/get ($File . ".txt") size ] > 0) \ - ("Output exceeds file read size.") ("No output.") ] ]) }); - /file/remove "tmpfs/telegram-chat"; + message=([ $SymbolForNotification "gear" ] . "Command:\n" . $Command . "\n\n" . \ + $State . [ $IfThenElse ([ :len $Content ] > 0) \ + ([ $SymbolForNotification "memo" ] . "Output:\n" . $Content) \ + ([ $SymbolForNotification "memo" ] . "No output.") ]) }); + $RmDir "tmpfs/telegram-chat"; } else={ - $LogPrintExit2 info $0 ("The command from update " . $UpdateID . " failed syntax validation!") false; - $SendTelegram2 ({ origin=$0; chatid=$ChatID; silent=false; replyto=$MessageId; \ + $LogPrint info $ScriptName ("The command from update " . $UpdateID . " failed syntax validation!"); + $SendTelegram2 ({ origin=$ScriptName; chatid=($Chat->"id"); silent=false; \ + replyto=($Message->"message_id"); threadid=$ThreadId; \ subject=([ $SymbolForNotification "speech-balloon" ] . "Telegram Chat"); \ - message=("Command:\n" . $Text . "\n\nThe command failed syntax validation!") }); + message=([ $SymbolForNotification "gear" ] . "Command:\n" . $Command . "\n\n" . \ + [ $SymbolForNotification "cross-mark" ] . "The command failed syntax validation!") }); } } - } - } else={ - :local Message ("Received a message from untrusted contact " . \ - [ $IfThenElse ($FromUserName = false) "without username" ("'" . $FromUserName . "'") ] . \ - " (ID " . $FromID . ") in update " . $UpdateID . "!"); - :if ($Text ~ ("^! *" . [ $EscapeForRegEx $Identity ] . "\$")) do={ - $LogPrintExit2 warning $0 $Message false; - $SendTelegram2 ({ origin=$0; chatid=$ChatID; silent=false; replyto=$MessageId; \ - subject=([ $SymbolForNotification "speech-balloon" ] . "Telegram Chat"); \ - message=("You are not trusted.") }); } else={ - $LogPrintExit2 info $0 $Message false; + :local MessageText ("Received a message from untrusted contact " . \ + [ $IfThenElse ([ :len ($From->"username") ] = 0) "without username" ("'" . $From->"username" . "'") ] . \ + " (ID " . $From->"id" . ") in update " . $UpdateID . "!"); + :if ($Command ~ ("^! *" . [ $EscapeForRegEx $Identity ] . "\$")) do={ + $LogPrint warning $ScriptName $MessageText; + $SendTelegram2 ({ origin=$ScriptName; chatid=($Chat->"id"); silent=false; \ + replyto=($Message->"message_id"); threadid=$ThreadId; \ + subject=([ $SymbolForNotification "speech-balloon" ] . "Telegram Chat"); \ + message=("You are not trusted.") }); + } else={ + $LogPrint info $ScriptName $MessageText; + } } + } else={ + $LogPrint debug $ScriptName ("Already handled update " . $UpdateID . "."); } - } else={ - $LogPrintExit2 debug $0 ("Already handled update " . $UpdateID . ".") false; } + :set TelegramChatOffset ([ :pick $TelegramChatOffset 1 3 ], \ + [ $IfThenElse ($UpdateID >= $TelegramChatOffset->2) ($UpdateID + 1) ($TelegramChatOffset->2) ]); +} on-error={ + :global ExitError; $ExitError $ExitOK [ :jobname ]; } -:set TelegramChatOffset ([ :pick $TelegramChatOffset 1 3 ], \ - [ $IfThenElse ($UpdateID >= $TelegramChatOffset->2) ($UpdateID + 1) ($TelegramChatOffset->2) ]); |