From 8a900dce00bf08acc1347ff9befedd634ee76adb Mon Sep 17 00:00:00 2001 From: Christian Hesse Date: Fri, 3 Feb 2023 20:29:10 +0100 Subject: telegram-chat: delay confirmation of updates MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Several devices can communicate with the same bot, and we want all of them to receive their updates. However this can be tricky, as... * ... sometimes internet connection can be unreliable or saturated. * ... device can be busy with long running command. * ... the Telegram bot api servers seem to implement what ever kind of rate limiting. Anybody can give details? So let's confirm the update id after third request only. 😁 This gives delayed devices some extra chances to catch up. --- telegram-chat | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) (limited to 'telegram-chat') diff --git a/telegram-chat b/telegram-chat index d7b6f18..16b6e9e 100644 --- a/telegram-chat +++ b/telegram-chat @@ -37,8 +37,8 @@ $ScriptLock $0; $WaitFullyConnected; -:if ([ :typeof $TelegramChatOffset ] != "num") do={ - :set TelegramChatOffset 0; +:if ([ :typeof $TelegramChatOffset ] != "array") do={ + :set TelegramChatOffset { 0; 0; 0 }; } :if ([ $CertificateAvailable "Go Daddy Secure Certificate Authority - G2" ] = false) do={ @@ -65,16 +65,16 @@ $WaitFullyConnected; :do { :set Data ([ /tool/fetch check-certificate=yes-without-crl output=user \ ("https://api.telegram.org/bot" . $TelegramTokenId . "/getUpdates?offset=" . \ - $TelegramChatOffset . "&allowed_updates=%5B%22message%22%5D") as-value ]->"data"); + $TelegramChatOffset->0 . "&allowed_updates=%5B%22message%22%5D") as-value ]->"data"); :set Data [ :pick $Data ([ :find $Data "[" ] + 1) ([ :len $Data ] - 2) ]; } on-error={ $LogPrintExit2 info $0 ("Failed getting updates from Telegram.") true; } +:local UpdateID 0; :foreach Update in=[ :toarray $Data ] do={ - :local UpdateID [ $JsonGetKey $Update "update_id" ]; - :if ($UpdateID >= $TelegramChatOffset) do={ - :set TelegramChatOffset ($UpdateID + 1); + :set UpdateID [ $JsonGetKey $Update "update_id" ]; + :if ($UpdateID >= $TelegramChatOffset->2) do={ :local Trusted false; :local Message [ $JsonGetKey $Update "message" ]; :local From [ $JsonGetKey $Message "from" ]; @@ -139,3 +139,5 @@ $WaitFullyConnected; } } } +:set TelegramChatOffset ([ :pick $TelegramChatOffset 1 3 ], \ + [ $IfThenElse ($UpdateID > 0) ($UpdateID + 1) ($TelegramChatOffset->2) ]); -- cgit v1.2.3-70-g09d2