aboutsummaryrefslogtreecommitdiffstats
path: root/telegram-chat.rsc
blob: 9ae596700d789619e31bfc457ac341ab699fdd9b (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
#!rsc by RouterOS
# RouterOS script: telegram-chat
# Copyright (c) 2023-2024 Christian Hesse <mail@eworm.de>
# https://git.eworm.de/cgit/routeros-scripts/about/COPYING.md
#
# requires RouterOS, version=7.12
#
# use Telegram to chat with your Router and send commands
# https://git.eworm.de/cgit/routeros-scripts/about/doc/telegram-chat.md

:global GlobalFunctionsReady;
:while ($GlobalFunctionsReady != true) do={ :delay 500ms; }

:do {
  :local ScriptName [ :jobname ];

  :global Identity;
  :global TelegramChatActive;
  :global TelegramChatGroups;
  :global TelegramChatId;
  :global TelegramChatIdsTrusted;
  :global TelegramChatOffset;
  :global TelegramChatRunTime;
  :global TelegramMessageIDs;
  :global TelegramRandomDelay;
  :global TelegramTokenId;

  :global CertificateAvailable;
  :global EitherOr;
  :global EscapeForRegEx;
  :global GetRandom20CharAlNum;
  :global IfThenElse;
  :global LogPrint;
  :global MAX;
  :global MIN;
  :global MkDir;
  :global ParseJson;
  :global RandomDelay;
  :global ScriptLock;
  :global SendTelegram2;
  :global SymbolForNotification;
  :global ValidateSyntax;
  :global WaitForFile;
  :global WaitFullyConnected;

  :if ([ $ScriptLock $ScriptName ] = false) do={
    :error false;
  }

  $WaitFullyConnected;

  :if ([ :typeof $TelegramChatOffset ] != "array") do={
    :set TelegramChatOffset { 0; 0; 0 };
  }
  :if ([ :typeof $TelegramRandomDelay ] != "num") do={
    :set TelegramRandomDelay 0;
  }

  :if ([ $CertificateAvailable "Go Daddy Secure Certificate Authority - G2" ] = false) do={
    $LogPrint warning $ScriptName ("Downloading required certificate failed.");
    :error false;
  }

  $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");
        }
      }
    }
  }

  :if ($Data = false) do={
    $LogPrint warning $ScriptName ("Failed getting updates from Telegram.");
    :error false;
  }

  :local UpdateID 0;
  :local Uptime [ /system/resource/get uptime ];
  :foreach UpdateArray in=([ $ParseJson $Data ]->"result") do={
    :local Update [ $ParseJson $UpdateArray ];
    :set UpdateID ($Update->"update_id");
    :local Message [ $ParseJson ($Update->"message") ];
    :local IsReply [ :len ($Message->"reply_to_message") ];
    :local IsMyReply ($TelegramMessageIDs->([ $ParseJson ($Message->"reply_to_message") ]->"message_id"));
    :if (($IsMyReply = 1 || $TelegramChatOffset->0 > 0 || $Uptime > 5m) && $UpdateID >= $TelegramChatOffset->2) do={
      :local Trusted false;
      :local Chat [ $ParseJson ($Message->"chat") ];
      :local From [ $ParseJson ($Message->"from") ];

      :foreach IdsTrusted in=($TelegramChatId, $TelegramChatIdsTrusted) do={
        :if ($From->"id" = $IdsTrusted || $From->"username" = $IdsTrusted) do={
          :set Trusted true;
        }
      }

      :if ($Trusted = true) do={
        :local Done false;
        :if ($Message->"text" = "?") do={
          $LogPrint info $ScriptName ("Sending notice for update " . $UpdateID . ".");
          $SendTelegram2 ({ origin=$ScriptName; chatid=($Chat->"id"); silent=true; replyto=($Message->"message_id"); \
            subject=([ $SymbolForNotification "speech-balloon" ] . "Telegram Chat"); \
            message=("Online" . [ $IfThenElse $TelegramChatActive " (and active!)" ] . ", awaiting your commands!") });
          :set Done true;
        }
        :if ($Done = false && [ :pick ($Message->"text") 0 1 ] = "!") do={
          :if ($Message->"text" ~ ("^! *(" . [ $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 = 0 && $TelegramChatActive = true)) && [ :len ($Message->"text") ] > 0) do={
          :if ([ $ValidateSyntax ($Message->"text") ] = true) do={
            :local State "";
            :local File ("tmpfs/telegram-chat/" . [ $GetRandom20CharAlNum 6 ]);
            :if ([ $MkDir "tmpfs/telegram-chat" ] = false) do={
              $LogPrint error $ScriptName ("Failed creating directory!");
              :error false;
            }
            $LogPrint info $ScriptName ("Running command from update " . $UpdateID . ": " . $Message->"text");
            :execute script=(":do {\n" . $Message->"text" . "\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 ([ $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 ([ $SymbolForNotification "cross-mark" ] . "The command failed with an error!\n\n");
            }
            :local Content [ /file/get $File contents ];
            $SendTelegram2 ({ origin=$ScriptName; chatid=($Chat->"id"); silent=true; replyto=($Message->"message_id"); \
              subject=([ $SymbolForNotification "speech-balloon" ] . "Telegram Chat"); \
              message=([ $SymbolForNotification "gear" ] . "Command:\n" . $Message->"text" . "\n\n" . \
                $State . [ $IfThenElse ([ :len $Content ] > 0) \
                ([ $SymbolForNotification "memo" ] . "Output:\n" . $Content) [ $IfThenElse ([ /file/get $File size ] > 0) \
                ([ $SymbolForNotification "warning-sign" ] . "Output exceeds file read size.") \
                ([ $SymbolForNotification "memo" ] . "No output.") ] ]) });
            /file/remove "tmpfs/telegram-chat";
          } else={
            $LogPrint info $ScriptName ("The command from update " . $UpdateID . " failed syntax validation!");
            $SendTelegram2 ({ origin=$ScriptName; chatid=($Chat->"id"); silent=false; replyto=($Message->"message_id"); \
              subject=([ $SymbolForNotification "speech-balloon" ] . "Telegram Chat"); \
              message=([ $SymbolForNotification "gear" ] . "Command:\n" . $Message->"text" . "\n\n" . \
                [ $SymbolForNotification "cross-mark" ] . "The command failed syntax validation!") });
          }
        }
      } else={
        :local MessageText ("Received a message from untrusted contact " . \
          [ $IfThenElse ([ :len ($From->"username") ] = 0) "without username" ("'" . $From->"username" . "'") ] . \
          " (ID " . $From->"id" . ") in update " . $UpdateID . "!");
        :if ($Message->"text" ~ ("^! *" . [ $EscapeForRegEx $Identity ] . "\$")) do={
          $LogPrint warning $ScriptName $MessageText;
          $SendTelegram2 ({ origin=$ScriptName; chatid=($Chat->"id"); silent=false; replyto=($Message->"message_id"); \
            subject=([ $SymbolForNotification "speech-balloon" ] . "Telegram Chat"); \
            message=("You are not trusted.") });
        } else={
          $LogPrint info $ScriptName $MessageText;
        }
      }
    } else={
      $LogPrint debug $ScriptName ("Already handled update " . $UpdateID . ".");
    }
  }
  :set TelegramChatOffset ([ :pick $TelegramChatOffset 1 3 ], \
    [ $IfThenElse ($UpdateID >= $TelegramChatOffset->2) ($UpdateID + 1) ($TelegramChatOffset->2) ]);
} on-error={ }