function threadHandle(runner, url, args, resolve, reject) -- обработка effil потока без блокировок
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
function requestRunner() -- создание effil потока с функцией https запроса
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
function async_http_request(url, args, resolve, reject)
local runner = requestRunner()
if not reject then reject = function() end end
lua_thread.create(function()
threadHandle(runner, url, args, resolve, reject)
end)
end
function send(msg)
msg = msg:gsub('{......}', '')
msg = u8(msg)
msg = url_encode(msg)
async_http_request('https://api.vk.com/method/messages.send', 'user_id='..user_id.v..'&message='..msg..'&access_token=' .. access_token .. '&v=5.80',
function (result)
local t = decodeJson(result)
if not t then
print(result)
return
end
if t.error then
vkerrsend = 'Ошибка!\nКод: ' .. t.error.error_code .. ' Причина: ' .. t.error.error_msg
return
end
vkerrsend = nil
end)
end
function url_encode(str)
local str = string.gsub(str, "\\", "\\")
local str = string.gsub(str, "([^%w])", char_to_hex)
return str
end
function char_to_hex(str)
return string.format("%%%02X", string.byte(str))
end