User Tools

Site Tools


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

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("%H:%M", os.time())) .. " o'clock!"  -- your message that will be sent
    local condition_to_send = (tonumber("%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
        first_request_no_chat_id = false
        chat_id = R("chat_id")
    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 = ''.. botToken .. "/getUpdates"
            DEBUG(initialisation_request_ulr )
            c = cURL.easy_init()
            local res = ""
            writefunction = function(str)
                                res = res .. str;
            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] < 0 then
                    new_chat_id = tostring(table.result[1]
                    WriteReg("chat_id", new_chat_id)
                                -- work branch  
            lastSentTime = R("telegram_last_sent_time")
            --        local condition_to_send = (tonumber("%s")) % 10 == 0 and now - lastSentTime >= ( 1 * 60 - 5))
            if condition_to_send == true then
                local url = ''.. botToken .. '/sendMessage?chat_id=' .. chat_id .. '&text=' .. urlencode(message);
                local res = "";
                c = cURL.easy_init()
                writefunction = function(str)
                                res = res .. str;
                local table = cjson.decode(res)
                local error_code = nil
                if table.ok == false then
                    error_code = table.error_code
                    lastErrorCode = error_code
                    lastSentTime = tonumber("%s"))
                    -- DEBUG(lastErrorCode) 
                    WriteReg("telegram_last_sent_status_unsuccesful", lastErrorCode); 
                    lastSentTime = tonumber("%s"))
                    lastSentTimeSuccesful = lastSentTime
                    lastStatus = table.result.message_id
                    WriteReg("telegram_last_sent_status", lastStatus)
                WriteReg("telegram_last_sent_time", lastSentTime); -- Останній час повідомлення в Telegram (DS15@WebHMI)
                WriteReg("telegram_last_sent_time_succesful", lastSentTimeSuccesful);
    -- 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, " ", "+")
        return str    

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