User Tools

Site Tools


bot_telegram_api

Send via Telegram bot messages to multiply persons chat from Lua via Telegram API

Nota bene,
This bot will work only with Raspberry PI and VirtualBox machine.

It is purpose is the ability to be invited in the chat.

OTHERWISE, please use Level 2 bot, which is running on the Level2 server, unlike this one, which should be ran on VM via Lua script.

When WebHMI is connected to internet it is possible to send Telegram messages via Telegram API.

There is a need to create a new bot via @BotFather. Send him /start command. Then it will show all of comands you can use to create and manage your bots. Pick /newbot command.

Then type in the name of bot. It will be telegram link, like @BotFather_bot for example. The only note, all of bot names should end with regular expression _bot When you will finish the creation you will get your own bot token.

Keep it secure, because everyone can get control if it is compromised.

Copy HTTP API Token to botToken variable in the first line of script.

Also, there is a few registers should be created to work correctly. There is a register map to import to your project to make creation easier.

If it is unable to import it with tool, you should create it manually.
Download register map.zip

Copypaste that script to you device.

- TelegramChatBot.lua
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

At the rest, invite that bot to your chat.

Do not forget to enable bot access to messages in BotFather's settings.

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