diff --git a/WebSocket.lua b/WebSocket.lua index 1834a33..8625981 100644 --- a/WebSocket.lua +++ b/WebSocket.lua @@ -23,43 +23,66 @@ local ws = function (dict) print(msg) end local server = game:GetService('HttpService') - local id = server:RequestAsync({ - ["Url"] = BaseUrl .. "api/connect/" .. JobId, + local response, status = server:RequestAsync({ + ["Url"] = BaseUrl .. "/api/connect/" .. JobId, ["Method"] = "PUT", - ["Body"] = dict.url - }).Body - print(id) - print(typeof(id)) - local function sendMessage(msg) - wait() - server:PostAsync(BaseUrl .. "api/send/" .. JobId .."/"..id, msg) - end - - local function close() - server:RequestAsync({ - ["Url"] = BaseUrl .. "api/close/" .. JobId .. "/" .. id, - ["Method"] = "DELETE" - }) - end - - local loop = coroutine.create(function() - while wait(50 / 1000) do - local msg = server:GetAsync(BaseUrl .. "api/poll/"..JobId.."/"..id) - if notExists(messages, msg) then - table.insert(messages, msg) - if notEmpty(msg) then - onMessage(msg) - end + ["Body"] = server:JSONEncode({["url"] = dict.url}), + ["Headers"] = {["Content-Type"] = "application/json"} + }) + if response.Success then + local id = response.Body + local function sendMessage(msg) + wait() + local resp = server:RequestAsync({ + ["Url"] = BaseUrl .. "/api/send/" .. JobId .."/"..id, + ["Method"] = "POST", + ["Body"] = server:JSONEncode({["data"] = msg}), + ["Headers"] = {["Content-Type"] = "application/json"} + }) + if not resp.Success then + error("Error Sending Message: " .. resp.StatusCode .. " " .. resp.StatusMessage) end end - end) - coroutine.resume(loop) - game:BindToClose(close) - return { - sendMessage = sendMessage, - onMessage = onMessage, - close = close - } + + local function close() + server:RequestAsync({ + ["Url"] = BaseUrl .. "/api/close/" .. JobId .. "/" .. id, + ["Method"] = "DELETE" + }) + end + + local loop = coroutine.create(function() + while wait(0.1) do + print("poll") + local response = server:RequestAsync({ + ["Url"] = BaseUrl .. "/api/poll/"..JobId.."/".. id, + ["Method"] = "GET" + }) + + if response.Success then + local msg = response.Body + -- Rest of the code + else + error("Error Polling Messages: " .. response.StatusCode .. " " .. response.StatusMessage) + end + if notExists(messages, msg) then + table.insert(messages, msg) + if notEmpty(msg) then + onMessage(msg) + end + end + end + end) + coroutine.resume(loop) + game:BindToClose(close) + return { + sendMessage = sendMessage, + onMessage = onMessage, + close = close + } + else + error("Error Connecting to Websocket Server: " .. response.StatusCode .. " " .. response.StatusMessage) + end end return ws