User Tools

Site Tools


bot_telegram_api

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Both sides previous revisionPrevious revision
Next revision
Previous revision
Last revisionBoth sides next revision
send_telegram_messages_via_api [2021/02/26 16:07] atolstovbot_telegram_api [2021/03/11 09:30] atolstov
Line 1: Line 1:
-====== Send Telegram messages to multiply persone chat from Lua via Telegram API ======+====== Send via Telegram bot messages to multiply persons chat from Lua via Telegram API ======
 <WRAP center round alert 60%> <WRAP center round alert 60%>
 Nota bene, \\  Nota bene, \\ 
Line 41: Line 41:
  
 <code lua - TelegramChatBot.lua> <code lua - TelegramChatBot.lua>
-local botToken = "0123456789:AAHiSspsO3DDg21oToh8Ucb6Wo6nTVxhEsV" --example of Token 
- 
-local bot_id = tonumber(string.sub(botToken, 1, string.find( botToken, ":")-1)) 
- 
 function main (userId) function main (userId)
 +    local botToken = "1556884060:AAFjT5F4IWXTbrcbuUkoL7qhDTrZCf8EA94" --example of Token
 +    local bot_id = tonumber(string.sub(botToken, 1, string.find( botToken, ":")-1))
 +     
 +    
 +    lastSentTime = R("telegram_last_sent_time")
  
-now = os.time(); +    -- function main (userId) 
-local message = "Hello, Telegram! It's " .. tostring(os.date("%H:%m")) .. " o'clock!"  -- your message that will be sent +      
-local condition_to_send = (tonumber(os.date("%s")) % 10 == 0 and now - lastSentTime >= ( 1 * 60 - 5)) +    now = os.time(); 
- +    local message = "Hello, Telegram! It's " .. tostring(os.date("%H:%M", os.time())) .. " o'clock!"  -- your message that will be sent 
-    -- check if it is initialisation or not +    TRACE(message) 
-if (R("chat_id")) == "" then +     
-    first_request_no_chat_id = true +     
-    chat_id = "" +    local condition_to_send = (tonumber(os.date("%s")) % 10 == 0 and now - lastSentTime >= ( 1 * 60 - 5)) 
-else +        -- check if it is initialisation or not 
-    first_request_no_chat_id = false +    if (R("chat_id")) == "" then 
-    chat_id = R("chat_id"+        first_request_no_chat_id = true 
-end +        -- chat_id = "" 
- +        -- return 
-                            -- initialisation branch +    else 
-    if first_request_no_chat_id == true then  +        first_request_no_chat_id = false 
-        local initialisation_request_ulr = 'https://api.telegram.org/bot'.. botToken .. "/getUpdates" +        chat_id = R("chat_id"
-        DEBUG(initialisation_request_ulr ) +    end 
-        c = cURL.easy_init() +    if first_request_no_chat_id then TRACE("first_request_no_chat_id " .. tostring(first_request_no_chat_id)) end 
-        c:setopt_timeout(5) +      
-        c:setopt_url(initialisation_request_ulr) +                                -- initialisation branch 
-        local res = "" +        if first_request_no_chat_id == true then  
-        c:perform({ +            local initialisation_request_ulr = 'https://api.telegram.org/bot'.. botToken .. "/getUpdates" 
-        writefunction = function(str) +            DEBUG(initialisation_request_ulr )
-                            res = res .. str; +
-                        end}) +
-                                DEBUG(res) +
-        local table = cjson.decode(res) +
-                --- Check when bot is invited to group +
-        if table.result[1].message.new_chat_participant.id == bot_id then +
-            new_chat_id = tostring(table.result[1].message.chat.id) +
-            WriteReg("chat_id", new_chat_id+
-        end +
-                            -- work branch   +
-    else  +
- +
-        lastSentTime = R("telegram_last_sent_time"+
-        --        local condition_to_send = (tonumber(os.date("%s")) % 10 == 0 and now - lastSentTime >= ( 1 * 60 - 5)) +
-        if condition_to_send == true then +
-            local url = 'https://api.telegram.org/bot'.. botToken .. '/sendMessage?chat_id=' .. chat_id .. '&text=' .. urlencode(message)+
-             +
-            local res = "";+
             c = cURL.easy_init()             c = cURL.easy_init()
-            c:setopt_url(url+            c:setopt_timeout(5
-            --INFO(message);+            c:setopt_url(initialisation_request_ulr) 
 +            local res = ""
             c:perform({             c:perform({
             writefunction = function(str)             writefunction = function(str)
-                            res = res .. str; +                                res = res .. str; 
-                        end}) +                            end}) 
-          +                                    DEBUG(res)
             local table = cjson.decode(res)             local table = cjson.decode(res)
-            local error_code nil+                    --- Check when bot is invited to group 
 +            for jj, jvalue in pairs ( table.result) do 
 +                if tonumber(table.result[jj].my_chat_member.chat.id) < 0 then 
 +                    new_chat_id tostring(table.result[1].my_chat_member.chat.id) 
 +                    WriteReg("chat_id", new_chat_id) 
 +                    break 
 +                end 
 +            end
                          
-            if table.ok == false then +                                -- work branch   
-                error_code = table.error_code +        else  
-                lastErrorCode = error_code +      
-                lastSentTime = tonumber(os.date("%s")) +            lastSentTime = R("telegram_last_sent_time"
-                -- DEBUG(lastErrorCode)  +            --        local condition_to_send = (tonumber(os.date("%s")) % 10 == 0 and now - lastSentTime >= ( 1 * 60 - 5)) 
-                WriteReg("telegram_last_sent_status_unsuccesful", lastErrorCode);  +            if condition_to_send == true then 
-             +                local url = 'https://api.telegram.org/bot'.. botToken .. '/sendMessage?chat_id=' .. chat_id .. '&text=' .. urlencode(message); 
-            else +      
-                lastSentTime = tonumber(os.date("%s")) +                local res = ""; 
-                lastSentTimeSuccesful = lastSentTime +                c = cURL.easy_init() 
-                lastStatus = table.result.message_id +                c:setopt_url(url) 
-                 +                --INFO(message); 
-                WriteReg("telegram_last_sent_status", lastStatus)+                c:perform({ 
 +                writefunction = function(str) 
 +                                res = res .. str; 
 +                            end}) 
 +      
 +                local table = cjson.decode(res) 
 +                local error_code = nil 
 +      
 +                if table.ok == false then 
 +                    error_code = table.error_code 
 +                    lastErrorCode = error_code 
 +                    lastSentTime = tonumber(os.date("%s")) 
 +                    -- DEBUG(lastErrorCode)  
 +                    WriteReg("telegram_last_sent_status_unsuccesful", lastErrorCode);  
 +      
 +                else 
 +                    lastSentTime = tonumber(os.date("%s")) 
 +                    lastSentTimeSuccesful = lastSentTime 
 +                    lastStatus = table.result.message_id 
 +      
 +                    WriteReg("telegram_last_sent_status", lastStatus) 
 +                end 
 +                c:close() 
 +                WriteReg("telegram_last_sent_time", lastSentTime); -- Останній час повідомлення в Telegram (DS15@WebHMI) 
 +                WriteReg("telegram_last_sent_time_succesful", lastSentTimeSuccesful);
             end             end
-            c:close() 
-            WriteReg("telegram_last_sent_time", lastSentTime); -- Останній час повідомлення в Telegram (DS15@WebHMI) 
-            WriteReg("telegram_last_sent_time_succesful", lastSentTimeSuccesful); 
         end         end
-    end+    -- end 
 +      
 + 
 end end
  
-function urlencode(str) +    function urlencode(str) 
-    if (str) then +        if (str) then 
-        str = string.gsub (str, "\n", "\r\n"+            str = string.gsub (str, "\n", "\r\n"
-        str = string.gsub (str, "([^%w ])", +            str = string.gsub (str, "([^%w ])", 
-        function (c) return string.format ("%%%02X", string.byte(c)) end) +            function (c) return string.format ("%%%02X", string.byte(c)) end) 
-        str = string.gsub (str, " ", "+")+            str = string.gsub (str, " ", "+") 
 +        end 
 +        return str    
     end     end
-    return str     
-end 
 </code> </code>
  
Line 134: Line 149:
  
 At the rest, invite that bot to your chat. At the rest, invite that bot to your chat.
 +
 +<WRAP center round tip 60%>
 +Do not forget to enable bot access to messages in BotFather's settings. 
 +</WRAP>
 +
  
 Run script and it will initialise. In the ''chat_id'' register will became id like ''//-123456789//''. From this moment, your ''message'' variable content will be sent to your Telegram chat, when your variable ''condition_to_send'' equals to **''true''** Run script and it will initialise. In the ''chat_id'' register will became id like ''//-123456789//''. From this moment, your ''message'' variable content will be sent to your Telegram chat, when your variable ''condition_to_send'' equals to **''true''**
 +
 +<WRAP center round download 60%>
 +{{ :telegram:telegram-api-bot-groups-chat-backup-2021-03-11-firmware-4.0_1_.zip |Sample Project (token used from @WHtest2_bot, human host @tolstov_x)}}
 +</WRAP>
 +
bot_telegram_api.txt · Last modified: 2021/03/11 09:31 by atolstov

Donate Powered by PHP Valid HTML5 Valid CSS Driven by DokuWiki