Удаленный запуск скриптов через Телеграм

Здесь выкладываем скрипты
Правила форума
Уважаемые Пользователи форума, обратите внимание!
Ни при каких обстоятельствах, Администрация форума, не несёт ответственности за какой-либо, прямой или косвенный, ущерб причиненный в результате использования материалов, взятых на этом Сайте или на любом другом сайте, на который имеется гиперссылка с данного Сайта. Возникновение неисправностей, потерю программ или данных в Ваших устройствах, даже если Администрация будет явно поставлена в известность о возможности такого ущерба.
Просим Вас быть предельно осторожными и внимательными, в использовании материалов раздела. Учитывать не только Ваши пожелания, но и границы возможностей вашего оборудования.
Ответить
goryn
Сообщения: 4
Зарегистрирован: 16 фев 2022, 14:49

Sertik писал(а): 19 июл 2023, 14:49 Глобокоуважаемый goryn (Горыныч по-нашему) !
Все хотят получить всё на блюдечке с голубой каёмочкой, вместо того, чтобы чуть самим поработать. А жаль.
Скриптописателей мало ...
Позволю себе немного пофлеймить. В ответ на мой вопрос вы написали "неохота", при том, что мой вопрос был к "кому-то". Скриптописателей ОЧЕНЬ немного, согласен, и тарелка с каемочкой вещь очень удобная, когда кто-то, кому это было критически важно - решил вопрос и готов поделиться этим добром с миром.
А просто так создать пост (не буду это называть пузырем в воду), ну это так себе реакция. Не хочу обидеть, однако пытаюсь немного осадить повышенное самолюбие.
Я для себя вопрос решил просто отключив скрипт, мой домашний роутер выживает и без него. К сожалению в данной ситуации, ковыряние под капотом микротиков не мой профессиональный выбор, а работа отжирает почти все время.


kreotoDr
Сообщения: 21
Зарегистрирован: 31 мар 2018, 09:13

Благодарю покорнейше автора!
Суть и принцип работы подобных реализаций понял. Все благополучно запустилось на RoS 7.11.2

Однако есть вопрос к автору и всем участники темы.
Как на базе подобного решения отправлять сообщения боту из группы?
Кроме того,
Для парсинга в скрипте идет четкая привязка к:

message_id
from
id XXXXXXXX

То есть с другого аккаунта телеги, будет другой id и скрипт не сработает


Sertik
Сообщения: 1601
Зарегистрирован: 15 сен 2017, 09:03

Делайте групповой чат, привязывайте к нему аккаунты пользователей и боты и всё сработает.


фрагменты скриптов, готовые работы, статьи, полезные приемы, ссылки
viewtopic.php?f=14&t=13947
kreotoDr
Сообщения: 21
Зарегистрирован: 31 мар 2018, 09:13

Благодарю, все получилось!
Проблема была в ситнаксе iD групового чата. Как оказалось нужно начинать со знака "-"


cocainus
Сообщения: 2
Зарегистрирован: 07 мар 2019, 20:09

Месяца три пользовался скриптом все ок, работает - нравится. Авторам огромное спасибо. Но. Внесу маленькую ремарку, давече я тут проапгрейдил свои домашние устройства, закупился миротами, на борту у которых имеет место WiFi Wave2. Ну, там контролер - RB5009UPr и 5шт Cap в виде сAP ax.
По существу, настроил я это все перенес скрипт на котроллер - и, не работает. Так вот, а не работает он, потому что у новых устройств с WiFi Wave2, а так же и не у совсем новых, но с установленным пакетом wifiwave2, изменилось название беспроводного интерфейса, вместо /interface wireless стало /interface wifiwave2. Отседова вывод, вывод правда не мой, а терминала: /system/script> run Telegram expected end of command (line 311 column 103).

В общем, подправил код, заменил в 311 строчке wireless на wifiwave2, и знаете, мне опять все понравилось.

Надо наверное как то унифицировать код в будущих версиях скрипта, что бы он работал там и сям. Спасибо.

P.S. Версия ROS 7.11.2


SergeyKRG
Сообщения: 5
Зарегистрирован: 14 авг 2023, 09:01

cocainus писал(а): 27 сен 2023, 23:28 Месяца три пользовался скриптом все ок, работает - нравится. Авторам огромное спасибо. Но. Внесу маленькую ремарку, давече я тут проапгрейдил свои домашние устройства, закупился миротами, на борту у которых имеет место WiFi Wave2. Ну, там контролер - RB5009UPr и 5шт Cap в виде сAP ax.
По существу, настроил я это все перенес скрипт на котроллер - и, не работает. Так вот, а не работает он, потому что у новых устройств с WiFi Wave2, а так же и не у совсем новых, но с установленным пакетом wifiwave2, изменилось название беспроводного интерфейса, вместо /interface wireless стало /interface wifiwave2. Отседова вывод, вывод правда не мой, а терминала: /system/script> run Telegram expected end of command (line 311 column 103).

В общем, подправил код, заменил в 311 строчке wireless на wifiwave2, и знаете, мне опять все понравилось.

Надо наверное как то унифицировать код в будущих версиях скрипта, что бы он работал там и сям. Спасибо.

P.S. Версия ROS 7.11.2
Спасибо большое , две недели тупил и искал причин.


ObScEnE
Сообщения: 2
Зарегистрирован: 10 авг 2017, 11:34

drpioneer писал(а): 12 июл 2023, 13:52 Добрый день.

Предлагаю попробовать обновленный вариант базового скрипта, без поддержки SATELLITE, и заодно проверить его работоспособность под ROS 7.10+:
Функционал Emoji убран на корню? К сожалению не разобрался как его вернуть...


Аватара пользователя
drpioneer
Сообщения: 149
Зарегистрирован: 30 май 2013, 10:20

Добрый день.

Предлагаю попробовать обновленную версию скрипта, в которой учтены накопившиеся замечания:

Код: Выделить всё




# TLGRM - combined notifications script & launch of commands (scripts & functions) via Telegram
# Script uses ideas by Sertik, Virtue, Dimonw, -13-, Mk51, Alice Tails, Chupaka, rextended, sebastia, drPioneer
# https://forummikrotik.ru/viewtopic.php?p=91375#p91375
# https://github.com/drpioneer/MikrotikTelegramMessageHandler
# tested on ROS 6.49.10 & 7.12
# updated 2023/11/20

:global scriptTlgrm;                                                                    # flag of running script: false=in progress, true=idle
:do {
    :local botID    "botXXXXXXXXXX:XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
    :local myChatID "-XXXXXXXXX";
    :local broadCast false;                                                             # non-addressed reception mode
    :local launchScr true;                                                              # permission to execute scripts
    :local launchFnc true;                                                              # permission to perform functions
    :local launchCmd true;                                                              # permission to execute commands
    :local sysInfo   true;                                                              # system information broadcast to Telegram
    :local userInfo  false;                                                             # user information broadcast to Telegram
    :local emoList {
        "cherry"="%F0%9F%8D%92"; "monkey"="%F0%9F%90%92"; "crown"="%F0%9F%91%91";
        "smile"="%F0%9F%98%8E"; "bell"="%F0%9F%94%94"; "dancer"="%F0%9F%92%83"};        # emoji list: https://apps.timwhitlock.info/emoji/tables/unicode
    :local emoDev  ($emoList->"cherry");                                                # device emoji in chat
    :global timeAct;                                                                    # time when the last command was executed
    :global timeLog;                                                                    # time when the log entries were last sent

    # --------------------------------------------------------------------------------- # function of converting CP1251 to UTF8 in URN-standart
    :local CP1251toUTF8inURN do={                                                       # https://forum.mikrotik.com/viewtopic.php?p=967513#p967513
        :if (([:typeof $1]!="str") or ([:len $1]=0)) do={:return ""};                   # https://habr.com/ru/articles/232385/#urn
        :local cp1251 {
            "\00";"\01";"\02";"\03";"\04";"\05";"\06";"\07";"\08";"\09";"\0A";"\0B";"\0C";"\0D";"\0E";"\0F";
            "\10";"\11";"\12";"\13";"\14";"\15";"\16";"\17";"\18";"\19";"\1A";"\1B";"\1C";"\1D";"\1E";"\1F";
            "\20";"\22";"\26";"\2B";"\3C";"\3E";"\5B";"\5C";"\5D";"\5E";"\60";"\7B";"\7C";"\7D";"\7E";"\7F";
            "\80";"\81";"\82";"\83";"\84";"\85";"\86";"\87";"\88";"\89";"\8A";"\8B";"\8C";"\8D";"\8E";"\8F";
            "\90";"\91";"\92";"\93";"\94";"\95";"\96";"\97";"\98";"\99";"\9A";"\9B";"\9C";"\9D";"\9E";"\9F";
            "\A0";"\A1";"\A2";"\A3";"\A4";"\A5";"\A6";"\A7";"\A8";"\A9";"\AA";"\AB";"\AC";"\AD";"\AE";"\AF";
            "\B0";"\B1";"\B2";"\B3";"\B4";"\B5";"\B6";"\B7";"\B8";"\B9";"\BA";"\BB";"\BC";"\BD";"\BE";"\BF";
            "\C0";"\C1";"\C2";"\C3";"\C4";"\C5";"\C6";"\C7";"\C8";"\C9";"\CA";"\CB";"\CC";"\CD";"\CE";"\CF";
            "\D0";"\D1";"\D2";"\D3";"\D4";"\D5";"\D6";"\D7";"\D8";"\D9";"\DA";"\DB";"\DC";"\DD";"\DE";"\DF";
            "\E0";"\E1";"\E2";"\E3";"\E4";"\E5";"\E6";"\E7";"\E8";"\E9";"\EA";"\EB";"\EC";"\ED";"\EE";"\EF";
            "\F0";"\F1";"\F2";"\F3";"\F4";"\F5";"\F6";"\F7";"\F8";"\F9";"\FA";"\FB";"\FC";"\FD";"\FE";"\FF"}
        :local utf8 {
            "00";"01";"02";"03";"04";"05";"06";"07";"08";"09";"0A";"0B";"0C";"0D";"0E";"0F";
            "10";"11";"12";"13";"14";"15";"16";"17";"18";"19";"1A";"1B";"1C";"1D";"1E";"1F";
            "20";"22";"26";"2B";"3C";"3E";"5B";"5C";"5D";"5E";"60";"7B";"7C";"7D";"7E";"7F";
            "D082";"D083";"E2809A";"D193";"E2809E";"E280A6";"E280A0";"E280A1";"E282AC";"E280B0";"D089";"E280B9";"D08A";"D08C";"D08B";"D08F";
            "D192";"E28098";"E28099";"E2809C";"E2809D";"E280A2";"E28093";"E28094";"EFBFBD";"E284A2";"D199";"E280BA";"D19A";"D19C";"D19B";"D19F";
            "C2A0";"D08E";"D19E";"D088";"C2A4";"D290";"C2A6";"C2A7";"D081";"C2A9";"D084";"C2AB";"C2AC";"534859";"C2AE";"D087";
            "C2B0";"C2B1";"D086";"D196";"D291";"C2B5";"C2B6";"C2B7";"D191";"E28496";"D194";"C2BB";"D198";"D085";"D195";"D197";
            "D090";"D091";"D092";"D093";"D094";"D095";"D096";"D097";"D098";"D099";"D09A";"D09B";"D09C";"D09D";"D09E";"D09F";
            "D0A0";"D0A1";"D0A2";"D0A3";"D0A4";"D0A5";"D0A6";"D0A7";"D0A8";"D0A9";"D0AA";"D0AB";"D0AC";"D0AD";"D0AE";"D0AF";
            "D0B0";"D0B1";"D0B2";"D0B3";"D0B4";"D0B5";"D0B6";"D0B7";"D0B8";"D0B9";"D0BA";"D0BB";"D0BC";"D0BD";"D0BE";"D0BF";
            "D180";"D181";"D182";"D183";"D184";"D185";"D186";"D187";"D188";"D189";"D18A";"D18B";"D18C";"D18D";"D18E";"D18F"}
        :local res ""; :local urn "";
        :for i from=0 to=([:len $1]-1) do={
            :local sym [:pick $1 $i ($i+1)];                                            # source symbol
            :local idx [:find $cp1251 $sym];                                            # index
            :local utf ($utf8->$idx);                                                   # target symbol
            :if ([:len $utf]=0) do={:set urn $sym}
            :if ([:len $utf]=2) do={:set urn "%$[:pick $utf 0 2]"}
            :if ([:len $utf]=4) do={:set urn "%$[:pick $utf 0 2]%$[:pick $utf 2 4]"}
            :if ([:len $utf]=6) do={:set urn "%$[:pick $utf 0 2]%$[:pick $utf 2 4]%$[:pick $utf 4 6]"}
            :set res "$res$urn";
        }
        :return $res;
    }

    # --------------------------------------------------------------------------------- # function of converting to lowercase letters
    :local LowerCase do={                                                               # https://forum.mikrotik.com/viewtopic.php?p=714396#p714396
        :if ([:typeof $1]!="str" or [:len $1]=0) do={:return ""}
        :local lower "abcdefghijklmnopqrstuvwxyz";
        :local upper "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        :local res "";
        :for i from=0 to=([:len $1]-1) do={
            :local chr [:pick $1 $i];
            :local pos [:find $upper $chr];
            :if ($pos>-1) do={:set chr [:pick $lower $pos]};
            :set res ($res.$chr);
        }
        :return $res;
    }

    # --------------------------------------------------------------------------------- # telegram messenger response parsing function
    :local MsgParser do={                                                               # https://habr.com/ru/post/482802/
        :if ([:typeof $1]!="str" or [:len $1]=0) do={:return ""}
        :local variaMod ("\"$2\"");
        :if ([:len [:find $1 $variaMod -1]]=0) do={:return "unknown"}
        :local startLoc ([:find $1 $variaMod -1]+[:len $variaMod]+1);
        :local commaLoc  [:find $1 "," $startLoc];
        :local brakeLoc  [:find $1 "}" $startLoc];
        :local endLoc $commaLoc;
        :local startSymbol [:pick $1 $startLoc];
        :if ($brakeLoc!=0 && ($commaLoc=0 or $brakeLoc<$commaLoc)) do={:set endLoc $brakeLoc}
        :if ($startSymbol="{") do={:set endLoc ($brakeLoc+1)}
        :if ($3=true) do={:set startLoc ($startLoc+1); :set endLoc ($endLoc-1)}
        :if ($endLoc<$startLoc) do={:set endLoc ($startLoc+1)}
        :return [:pick $1 $startLoc $endLoc];
    }

    # --------------------------------------------------------------------------------- # time translation function to UNIX-time
    :global DateTime2EpochTLG do={                                                      # https://forum.mikrotik.com/viewtopic.php?t=75555#p994849
        :local dTime [:tostr $1]; :local yesterDay false;                               # parses date formats:  "hh:mm:ss","mmm/dd hh:mm:ss","mmm/dd/yyyy hh:mm:ss",
        /system clock;                                                                  #                       "yyyy-mm-dd hh:mm:ss","mm-dd hh:mm:ss"
        :local cYear [get date]; :if ($cYear~"....-..-..") do={:set cYear [:pick $cYear 0 4]} else={:set cYear [:pick $cYear 7 11]}
        :if ([:len $dTime]=10 or [:len $dTime]=11) do={:set dTime "$dTime 00:00:00"}
        :if ([:len $dTime]=15) do={:set dTime "$[:pick $dTime 0 6]/$cYear $[:pick $dTime 7 15]"}
        :if ([:len $dTime]=14) do={:set dTime "$cYear-$[:pick $dTime 0 5] $[:pick $dTime 6 14]"}
        :if ([:len $dTime]=8) do={:if ([:totime $1]>[get time]) do={:set yesterDay true}; :set dTime "$[get date] $dTime"}
        :if ([:tostr $1]="") do={:set dTime ("$[get date] $[get time]")}
        :local vDate [:pick $dTime 0 [:find $dTime " " -1]];
        :local vTime [:pick $dTime ([:find $dTime " " -1]+1) [:len $dTime]];
        :local vGmt [get gmt-offset]; :if ($vGmt>0x7FFFFFFF) do={:set vGmt ($vGmt-0x100000000)}
        :if ($vGmt<0) do={:set vGmt ($vGmt*-1)}
        :local arrMn [:toarray "0,0,31,59,90,120,151,181,212,243,273,304,334"];
        :local vdOff [:toarray "0,4,5,7,8,10"];
        :local month [:tonum [:pick $vDate ($vdOff->2) ($vdOff->3)]];
        :if ($vDate~".../../....") do={
            :set vdOff [:toarray "7,11,1,3,4,6"];
            :set month ([:find "xxanebarprayunulugepctovecANEBARPRAYUNULUGEPCTOVEC" [:pick $vDate ($vdOff->2) ($vdOff->3)] -1]/2);
            :if ($month>12) do={:set month ($month-12)}
        }
        :local year [:pick $vDate ($vdOff->0) ($vdOff->1)]; :if ((($year-1968)%4)=0) do={:set ($arrMn->1) -1; :set ($arrMn->2) 30}
        :local toTd ((($year-1970)*365)+(($year-1968)/4)+($arrMn->$month)+([:pick $vDate ($vdOff->4) ($vdOff->5)]-1));
        :if ($yesterDay) do={:set toTd ($toTd-1)};                                      # bypassing ROS6.xx time format problem after 00:00:00
        :return (((((($toTd*24)+[:pick $vTime 0 2])*60)+[:pick $vTime 3 5])*60)+[:pick $vTime 6 8]-$vGmt);
    }

    # --------------------------------------------------------------------------------- # time conversion function from UNIX-time
    :global UnixToDateTimeTLG do={                                                      # https://forum.mikrotik.com/viewtopic.php?p=977170#p977170
        :local ZeroFill do={:return [:pick (100+$1) 1 3]}
        :local prMntDays [:toarray "0,0,31,59,90,120,151,181,212,243,273,304,334"];
        :local vGmt [:tonum [/system clock get gmt-offset]]; :if ($vGmt>0x7FFFFFFF) do={:set vGmt ($vGmt-0x100000000)}
        :if ($vGmt<0) do={:set vGmt ($vGmt*-1)}
        :local tzEpoch ($vGmt+[:tonum $1]);
        :if ($tzEpoch<0) do={:set tzEpoch 0};                                           # unsupported negative unix epoch
        :local yearStart (1970+($tzEpoch/31536000));
        :local tmpLeap (($yearStart-1968)/4); :if ((($yearStart-1968)%4)=0) do={:set ($prMntDays->1) -1; :set ($prMntDays->2) 30}
        :local tmpSec ($tzEpoch%31536000);
        :local tmpDays (($tmpSec/86400)-$tmpLeap);
        :if ($tmpSec<(86400*$tmpLeap) && (($yearStart-1968)%4)=0) do={
            :set tmpLeap ($tmpLeap-1); :set ($prMntDays->1) 0; :set ($prMntDays->2) 31; :set tmpDays ($tmpDays+1);
        }
        :if ($tmpSec<(86400*$tmpLeap)) do={:set yearStart ($yearStart-1); :set tmpDays ($tmpDays+365)}
        :local mnthStart 12 ; :while (($prMntDays->$mnthStart)>$tmpDays) do={:set mnthStart ($mnthStart-1)}
        :local dayStart [$ZeroFill (($tmpDays+1)-($prMntDays->$mnthStart))];
        :local timeStart (00:00:00+[:totime ($tmpSec%86400)]);
        :return "$yearStart/$[$ZeroFill $mnthStart]/$[$ZeroFill $dayStart] $timeStart";
    }

    # --------------------------------------------------------------------------------- # current time in nice format output function
    :local CurrentTime do={
        :global DateTime2EpochTLG;
        :global UnixToDateTimeTLG;
        :return [$UnixToDateTimeTLG [$DateTime2EpochTLG]];
    }

    # ================================================================================= # main body of the script ========================
    :local nameID [$LowerCase [/system identity get name]];                             # text ID of router
    :local currTime [$CurrentTime];                                                     # current time in nice format
    :put "$currTime\tStart of TLGRM on router:\t$nameID";
    :if ([:len $scriptTlgrm]=0) do={:set scriptTlgrm true};                             # creating a script running flag
    :if ($scriptTlgrm) do={                                                             # when script is active ->
        :set scriptTlgrm false;                                                         # script running flag is active 
        :if ([:len $timeAct]>0) do={:put "$[$CurrentTime]\tTime executed last command:\t$[$UnixToDateTimeTLG $timeAct]"}
        :if ([:len $timeLog]>0) do={:put "$[$CurrentTime]\tTime sent last log entries:\t$[$UnixToDateTimeTLG $timeLog]"}

        # ----------------------------------------------------------------------------- # part of the script body to execute via Telegram ---
        :put "$[$CurrentTime]\t*** Stage of launch via Telegram ***";                   # https://forummikrotik.ru/viewtopic.php?p=78085
        :local timeStmp [$DateTime2EpochTLG];
        :local urlString "https://api.telegram.org/$botID/getUpdates\?offset=-1&limit=1&allowed_updates=message";
        :local httpResp "";
        :if ([:len $timeAct]=0) do={:put "$[$CurrentTime]\tTime of last launch not found"; :set timeAct $timeStmp}
        :do {:set httpResp [/tool fetch url=$urlString as-value output=user]} on-error={}
        :if ([:len $httpResp]!=0) do={                                                  # when Telegram server responded to request ->
            :local content ($httpResp->"data");
            :if ([:len $content]>30) do={
                :local msgTxt [$MsgParser $content "text" true];
                :set   msgTxt [:pick $msgTxt ([:find $msgTxt "/" -1]+1) [:len $msgTxt]];
                :if ($msgTxt~"@") do={:set msgTxt [:pick $msgTxt 0 [:find $msgTxt "@"]]}
                :local newStr ""; :local change ""; :local msgAddr "";
                :for i from=0 to=([:len $msgTxt]-1) do={                                # cyclic replacement of character '_' by ' '
                    :local symb [:pick $msgTxt $i ($i+1)];
                    :if ($symb="_") do={:set change " "} else={:set change $symb} 
                    :set newStr "$newStr$change";
                }
                :set msgTxt $newStr;
                :if ($broadCast) do={:set msgAddr $nameID} else={
                    :set msgAddr [:pick $msgTxt 0 [:find $msgTxt " " -1]];
                    :set msgAddr [$LowerCase $msgAddr];
                    :if ([:len [:find $msgTxt " "]]=0) do={:set msgAddr "$msgTxt "}
                    :put "$[$CurrentTime]\tRecipient of Telegram message:\t$msgAddr";
                    :set msgTxt [:pick $msgTxt ([:find $msgTxt $msgAddr -1]+[:len $msgAddr]+1) [:len $msgTxt]];
                }
                :if ( [:pick $msgTxt 0 1]= "\$") do={:set msgTxt [:pick $msgTxt 1 [:len $msgTxt]]}
                :if ([:pick $msgTxt 0 2]="[\$" && [:pick $msgTxt ([:len $msgTxt]-1) [:len $msgTxt]]="]") do={
                    :set msgTxt [:pick $msgTxt 2 ([:len $msgTxt]-1)];                   # skipping prefix "$"  or [$ .....]
                }
                :if ($msgAddr=$nameID or $msgAddr="forall") do={
                    :local chatID [$MsgParser [$MsgParser $content "chat"] "id"];
                    :local userNm [$MsgParser $content "username"];
                    :set timeStmp [$MsgParser $content "date"];
                    :put "$[$CurrentTime]\tSender of Telegram message:\t$userNm";
                    :put "$[$CurrentTime]\tCommand to execute:\t\t$msgTxt";
                    :local restline [];
                    :if ([:len [:find $msgTxt " "]]!=0) do={
                        :set restline [:pick $msgTxt  ([:find $msgTxt " "]+1) [:len $msgTxt]];
                        :set msgTxt [:pick $msgTxt 0 [:find $msgTxt " "]];
                    }
                    :if ($chatID=$myChatID && $timeAct<$timeStmp) do={
                        :set timeAct $timeStmp;
                        :if ([/system script environment find name=$msgTxt]!="" && $launchFnc) do={
                            :if (([/system script environment get [/system script environment find name=$msgTxt] value]="(code)")\
                                or [:len [:find [/system script environment get [/system script environment find name=$msgTxt] value] "(eval"]]>0) do={
                                :put "$[$CurrentTime]\tRight time to launch function";
                                :log warning "Telegram user $userNm launches function: $msgTxt";
                                :execute script="[:parse [\$$msgTxt $restline]]";
                            } else={
                                :put "$[$CurrentTime]\t'$msgTxt' is a global variable and is not launched";
                                :log warning "'$msgTxt' is a global variable and is not launched";
                            }
                        }
                        :if ([:pick $msgTxt 0 1]="\5C") do={                            # allow to perform emoji
                            :set msgTxt [:pick $msgTxt 1 [:len $msgTxt]];
                            :if ([:find $msgTxt "\5C"]!=0) do={
                                :local first [:pick $msgTxt 0 [:find $msgTxt "\5C"]];
                                :local after [:pick $msgTxt  ([:find $msgTxt "\5C"]+1) [:len $msgTxt]];
                                :set msgTxt "$first$after";
                            }
                        }
                        :if ([/system script find name=$msgTxt]!="" && $launchScr) do={
                            :put "$[$CurrentTime]\tRight time to activate script";
                            :log warning "Telegram user $userNm activates script: $msgTxt";
                            :execute script="[[:parse \"[:parse [/system script get $msgTxt source]] $restline\"]]";
                        }
                        :if ([/system script find name=$msgTxt]="" && [/system script environment find name=$msgTxt]="" && $launchCmd) do={
                            :put "$[$CurrentTime]\tRight time to execute command";
                            :log warning "Telegram user $userNm is trying to execute command: $msgTxt";
                            :do {:execute script="[:parse \"/$msgTxt $restline\"]"} on-error={}
                        }
                    } else={:put "$[$CurrentTime]\tWrong time to launch"}
                } else={:put "$[$CurrentTime]\tNo command found for this device"}
            } else={:put "$[$CurrentTime]\tCompletion of response from Telegram"}
        } else={:put "$[$CurrentTime]\tNot response from Telegram"}
        :delay 1s;                                                                      # time difference between command execution and log broadcast

        # ----------------------------------------------------------------------------- # part of the script body for notifications in Telegram ----
        :put "$[$CurrentTime]\t*** Stage of broadcasting to Telegram ***";              # https://www.reddit.com/r/mikrotik/comments/onusoj/sending_log_alerts_to_telegram/
        :local logGet [:toarray [/log find (topics~"warning" or topics~"error" or topics~"critical" or topics~"caps" or topics~"wireless"\
            or topics~"dhcp" or topics~"firewall" or message~" logged ")]];             # list of potentially interesting log entries
        :local logCnt [:len $logGet];                                                   # counter of suitable log entries
        :local outMsg ""; :local tlgCnt 0;
        :if ([:len $timeLog]=0) do={                                                    # when time of last broadcast in Telegram not found ->
            :put "$[$CurrentTime]\tTime of the last log entry was not found";
            :set outMsg "$[/system clock get time] Telegram notification started";
            :set tlgCnt ($tlgCnt+1);
        }
        :if ($timeLog>[$DateTime2EpochTLG]) do={:set timeLog [$DateTime2EpochTLG]};     # correction when time of last broadcast to Telegram turned out to be from future
        :if ($logCnt>0) do={                                                            # when log entries are available ->
            :set logCnt ($logCnt-1);                                                    # index of last log entry
            :local lastTime [$DateTime2EpochTLG [/log get [:pick $logGet $logCnt] time]]; # time of the last message
            :local unixTim  "";
            :do {
                :local tempTim [/log get [:pick $logGet $logCnt] time];                 # message time in router format
                :set unixTim [$DateTime2EpochTLG $tempTim];                             # message time in UNIX format
                :if ($unixTim>$timeLog) do={                                            # selection of actualing log entries ->
                    :local tempMsg [/log get [:pick $logGet $logCnt] message];          # message body
# ------------------ system information output --- BEGIN ------------------
                    :if ($sysInfo) do={                                                 # broadcast SYSTEM information ->
                        :local preloadMessage "";
                        :local tempMac ""; :local tempAdr ""; :local tempCmt ""; :local tempHst "";
                        :local tempDyn ""; :local tempIfc "none"; :local tempStg ""; :local findMac "";
                        :if ($tempMsg~"([0-9A-F]{2}[:]){5}[0-9A-F]{2}") do={:set findMac [:pick $tempMsg ([:find $tempMsg ":"]-2) ([:find $tempMsg ":"]+15)]}
                        :if ($findMac!="") do={                                         # when any MAC address is detected ->
                            :do {
                                :set tempMac [/ip dhcp-server lease get [find mac-address=$findMac] mac-address];
                                :set tempCmt [/ip dhcp-server lease get [find mac-address=$findMac] comment];
                                :set tempHst [/ip dhcp-server lease get [find mac-address=$findMac] host-name];
                                :set tempDyn [/ip dhcp-server lease get [find mac-address=$findMac status="bound"] dynamic];
                                :set tempAdr [/ip dhcp-server lease get [find mac-address=$findMac status="bound"] address];
                            } on-error={}
                            :if ($tempMac="") do={                                      # when unfamiliar MAC address ->
                                :set preloadMessage "$tempTim $tempMsg [unfamiliar MAC]";
                            } else={
                                :if ($tempDyn!="") do={                                 # when DHCP-server lease client is actual ->
                                    :if (!$tempDyn && $tempCmt="") do={                 # when message with static IP & no comment about DHCP lease ->
                                        :set preloadMessage "$tempTim $tempMsg $tempHst $tempAdr [no comment about DHCP lease]";
                                    }
                                }
                            }
                        } else={:set preloadMessage "$tempTim $tempMsg"};               # output when message without MAC address
                        :if ($preloadMessage!="") do={
                            :set tlgCnt ($tlgCnt+1);
                            :set outMsg "$preloadMessage\n$outMsg";                     # attach to general message for Telegram
                            :put "$[$CurrentTime]\tAdded entry: $preloadMessage";
                        }
                    }
# ------------------- system information output ---- END ------------------
# ------------------- user information output --- BEGIN -------------------
                    :if ($userInfo) do={                                                # broadcast USER information ->
                        :local preloadMessage "";
                        :local tempMac ""; :local tempAdr ""; :local tempCmt ""; :local tempHst "";
                        :local tempDyn ""; :local tempIfc "none"; :local tempStg "";
                        :if ($tempMsg~" assigned ((25[0-5]|2[0-4][0-9]|[0-1]?[0-9][0-9]?)[.]){3}(25[0-5]|2[0-4][0-9]|[0-1]?[0-9][0-9]?)") do={
                            :if ($tempMsg~" to " ) do={:set tempAdr [:pick $tempMsg ([:find $tempMsg " assigned "]+10) ([:find $tempMsg "to" ]-1)]}; # specificity of ROS6
                            :if ($tempMsg~" for ") do={:set tempAdr [:pick $tempMsg ([:find $tempMsg " assigned "]+10) ([:find $tempMsg "for"]-1)]}; # specificity of ROS7
                        }
                        :if ($tempAdr!="") do={                                         # when address leasing DHCP server ->
                            :do {
                                :set tempCmt [/ip dhcp-server lease get [find address=$tempAdr] comment];
                                :set tempHst [/ip dhcp-server lease get [find address=$tempAdr] host-name];
                                :set tempDyn [/ip dhcp-server lease get [find address=$tempAdr] dynamic];
                                :set tempMac [/ip dhcp-server lease get [find address=$tempAdr] mac-address];
                                :set tempIfc [/interface bridge host get [find mac-address=$tempMac] on-interface];
                                :set tempStg [[:parse "[/interface wireless registration-table get [find last-ip=$tempAdr] signal-strength-ch0]"]];
                                :if ([:len $tempStg]=0) do={:set tempStg [[:parse "[/interface wifiwave2 registration-table get [find last-ip=$tempAdr] signal-strength-ch0]"]]}
                            } on-error={}
                            :if ($tempStg!="") do={:set tempStg ($tempStg."dBm")}
                            :local prefiksForLan "77_"; :local user1 "User1"; :local user2 "User2"; :local whereUser "PLACENAME";
                            :if ($tempDyn!="") do={
                                :if ($tempDyn) do={:set preloadMessage "$[($emoList->"smile")] $tempTim +$tempIfc $tempStg $tempAdr $tempHst"; # output when dynamic client
                                } else={:set preloadMessage "$tempCmt $tempTim +$tempIfc $tempStg $tempAdr $tempHst"};              # output when static client
                            }
                            :if ($tempCmt=$user1) do={:set preloadMessage "$[($emoList->"bell")] $tempTim $user1 at $whereUser"};   # output when user1
                            :if ($tempCmt=$user2) do={:set preloadMessage "$[($emoList->"smile")] $tempTim $user2 at $whereUser"};  # output when user2
                        }
                        :if ($preloadMessage!="") do={
                            :set tlgCnt ($tlgCnt+1);
                            :set outMsg "$preloadMessage\n$outMsg";                     # attach to general message for Telegram
                            :put "$[$CurrentTime]\tAdded entry: $preloadMessage";
                        }
                    }
                }
# -------------------- user information output ---- END -------------------
                :set logCnt ($logCnt-1);
            } while=($unixTim>$timeLog && $logCnt>-1 && [:len $outMsg]<4096);           # iterating through list of messages
            :if ([:len $timeLog]=0 or ([:len $timeLog]>0 && $timeLog!=$lastTime && [:len $outMsg]>8)) do={
                :set outMsg [$CP1251toUTF8inURN $outMsg];                               # converting MESSAGE to UTF8 in URN-standart
                :if ([:len $emoDev]!=0) do={:set emoDev ("$emoDev%20$nameID:")} else={:set emoDev ("$nameID:")}
                :if ($tlgCnt=1) do={:set outMsg "$emoDev%20$outMsg"} else={:set outMsg "$emoDev%0A$outMsg"}; # solitary message for pop-up notification on phone
                :if ([:len $outMsg]>4096) do={:set outMsg [:pick $outMsg 0 4096]};      # cutting MSG to 4096 bytes
                :set urlString "https://api.telegram.org/$botID/sendmessage\?chat_id=$myChatID&text=$outMsg";
                :put "$[$CurrentTime]\tGenerated string for Telegram:\t$urlString";
                :do {/tool fetch url=$urlString as-value output=user; :set timeLog $lastTime;
                } on-error={:put "$[$CurrentTime]\tUnsuccessful sending of message to Telegram"}
            } else={:put "$[$CurrentTime]\tThere are no log entries to send"}
        } else={:put "$[$CurrentTime]\tNecessary log entries were not found"}
        :put "$[$CurrentTime]\tEnd of TLGRM-script";
        /system script environment remove [find name~"TLG"];                            # clearing memory
        :set scriptTlgrm true;
    } else={:put "$currTime\tScript already being executed"; :put "$currTime\tEnd of TLGRM-script"}
} on-error={                                                                            # when emergency break script ->
    :put "Script error: something didn't work when sending a request to Telegram";
    :put "*** First, check the correctness of the values of the variables botID & myChatID ***";
    /system script environment remove [find name~"TLG"];                                # clearing memory
    :set scriptTlgrm true;
}




Savanna
Сообщения: 6
Зарегистрирован: 04 дек 2023, 07:30

Уважаемые создатели скрипта, спасибо за вашу работу. Но если можно, у меня нарисовался вопрос. :-):

А возможно ли отправлять своему скрипту на Микротике какую-нибудь строку в качестве аргумента? И если это возможно, не могли бы вы привести пример оформления подобной команды в Телеграм? А также пример строки в коде скрипта, которая читает этот аргумент?

Я хотел бы отправить своему скрипту IP адрес, чтобы скрипт подставил его в определенное место на Микротике.
drpioneer писал(а): 20 ноя 2023, 13:42 Предлагаю попробовать обновленную версию скрипта
Ваша новая версия скрипта работает как часы на RouterOS 7.12.1


Sertik
Сообщения: 1601
Зарегистрирован: 15 сен 2017, 09:03

Да, конечно. Можно отправлять как скрипту, так и функции. Чаще и более правильно для этого существуют функции. Почитайте как создавать функции на Микротик. Можно тут https://habr.com/ru/post/646663/


фрагменты скриптов, готовые работы, статьи, полезные приемы, ссылки
viewtopic.php?f=14&t=13947
Ответить