local effil = require('effil')
local json = require('json')
local api = nil
local id = nil
local function threadHandle(runner, url, args, resolve, reject)
local t = runner(url, args)
local r = t:get(0)
while not r do
r = t:get(0)
wait(0)
end
local status = t:status()
if status == 'completed' then
local ok, result = r[1], r[2]
if ok then resolve(result) else reject(result) end
elseif err then
reject(err)
elseif status == 'canceled' then
reject(status)
end
t:cancel(0)
end
local function requestRunner()
return effil.thread(function(u, a)
local https = require 'ssl.https'
local ok, result = pcall(https.request, u, a)
if ok then
return {true, result}
else
return {false, result}
end
end)
end
local function async_http_request(url, args, resolve, reject)
local runner = requestRunner()
if not reject then reject = function() end end
newTask(function()
threadHandle(runner, url, args, resolve, reject)
end)
end
function send(text, mid)
if api and id then
async_http_request('https://api.telegram.org/bot'..api..'/sendMessage?reply_to_message_id='..(mid and mid or 0)..'&chat_id='..id..'&text='..text, nil,
function(result)
local res = json.decode(result)
return print(res.ok and 'Successfully sent message.' or 'Message not sent. Error code: '..res.error_code..' Description: '..res.description)
end)
return true
end
return print('API not initialised.')
end