User Tools

Site Tools


bot_telegram_api

This is an old revision of the document!


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
local botToken = "0123456789:AAHiSspsO3DDg21oToh8Ucb6Wo6nTVxhEsV" --example of Token
 
local bot_id = tonumber(string.sub(botToken, 1, string.find( botToken, ":")-1))
 
function main (userId)
 
now = os.time();
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))
 
    -- check if it is initialisation or not
if (R("chat_id")) == "" then
    first_request_no_chat_id = true
    chat_id = ""
else
    first_request_no_chat_id = false
    chat_id = R("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
        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: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
 
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.

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

bot_telegram_api.1615451448.txt.gz · Last modified: 2021/03/11 08:30 by atolstov

Donate Powered by PHP Valid HTML5 Valid CSS Driven by DokuWiki