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") -- function main (userId) now = os.time(); local message = "Hello, Telegram! It's " .. tostring(os.date("%H:%M", os.time())) .. " o'clock!" -- your message that will be sent TRACE(message) local condition_to_send = (tonumber(os.date("%s")) % 10 == 0 and now - lastSentTime >= ( 1 * 60 - 5)) -- check if it is initialisation or not if (R("chat_id")) == "" then first_request_no_chat_id = true -- chat_id = "" -- return else first_request_no_chat_id = false chat_id = R("chat_id") end if first_request_no_chat_id then TRACE("first_request_no_chat_id " .. tostring(first_request_no_chat_id)) end -- initialisation branch if first_request_no_chat_id == true then local initialisation_request_ulr = 'https://api.telegram.org/bot'.. botToken .. "/getUpdates" DEBUG(initialisation_request_ulr ) c = cURL.easy_init() c:setopt_timeout(5) c:setopt_url(initialisation_request_ulr) local res = "" c:perform({ writefunction = function(str) res = res .. str; end}) DEBUG(res) local table = cjson.decode(res) --- 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 -- 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:setopt_url(url) --INFO(message); 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 -- end end function urlencode(str) if (str) then str = string.gsub (str, "\n", "\r\n") str = string.gsub (str, "([^%w ])", function (c) return string.format ("%%%02X", string.byte(c)) end) str = string.gsub (str, " ", "+") end return str end