# Script to send messages to a telegram bot # define required variables :local TOKEN "69568175l4:BAHslYpSWl2_DRw0DH-R18T1jWZ_AI8SllA"; :global ChatId; :local ChatBotUrl "https://api.telegram.org/bot$TOKEN"; :global TelegramQueue; # set debugging level (true/false) :global Debug false; # debugging function :global DebugFunc do={ :global Debug; :if ($Debug = true) do={ :put "**Debug: $1"; } } $DebugFunc "Starting processing of Telegram queue..."; # fix up queue if wrong data type :if ([:typeof $TelegramQueue] != "array") do={ :set TelegramQueue [:toarray ""]; $DebugFunc "Set TelegramQueue variable to type 'array'"; } if ([:len $ChatId] = 0) do={ # Initially we have no chat ID. We need to generate & store the # chat ID $DebugFunc "We do not have a chat ID yet. We'll retrieve one."; # perform a get updates call to find ID :local GetUpdateUrl "$ChatBotUrl/getUpdates"; :local BotResponse; :do { :set BotResponse [/tool fetch http-method=get url=$GetUpdateUrl check-certificate=no mode=https as-value output=user]; } on-error={ :local ErrorMessage "Error retrieving Chat ID value - Internet connection issue?"; :log error $ErrorMessage; $DebugFunc $ErrorMessage; :error $ErrorMessage; } $DebugFunc ("Bot response output: " . [:tostr $BotResponse]); $DebugFunc ("Bot response data field: " . $BotResponse->"data"); # extract the data response :local BotData ($BotResponse->"data"); # extract chat ID $DebugFunc "Extracting chat ID"; :local ChatIdStart [:find $BotData "\"chat\":{\"id\":" ]; :set ChatId [:pick $BotData ($ChatIdStart + 13) ($ChatIdStart + 23)]; $DebugFunc ("Extracted chat ID: " . $ChatId); # check if ChatId contains expected characters if ($ChatId ~ "[^1234567890]") do={ :local ErrorMessage "Chat ID appears to be incorrect format. Did you send an initial chat message?"; :log error $ErrorMessage; :set ChatId; :error $ErrorMessage; } } $DebugFunc ("Number of entries to process: " . [:len $TelegramQueue]); :foreach Message in=$TelegramQueue do={ # send message :local MessageUrl "$ChatBotUrl/sendMessage?chat_id=$ChatId&text=$Message"; $DebugFunc "Sending message to Telegram..."; $DebugFunc ("Message: $Message"); do { [/tool fetch http-method=get url=$MessageUrl check-certificate=no mode=https as-value output=user]; } on-error={ :local ErrorMessage "Error sending chatbot message"; :log error $ErrorMessage; $DebugFunc $ErrorMessage; } } # tidy up messages queue :set TelegramQueue [:toarray ""]; $DebugFunc "Script completed."; # tidy up global vars :set Debug; :set DebugFunc;