Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- local function download_file(url, target)
- local ht = http.get(url)
- local data = ht.readAll()
- ht.close()
- local file = fs.open(target, "w")
- file.write(data)
- file.close()
- end
- local jsonloc = "/json"
- if (not fs.exists(jsonloc)) then
- local newjsonloc = shell and shell.resolveProgram("json") or nil
- if type(newjsonloc) ~= "string" then
- download_file("https://pastebin.com/raw/4nRg9CHU", "/json")
- else
- jsonloc = newjsonloc
- end
- end
- os.loadAPI("/json")
- if not json then
- error("Failed to load JSON api, download it manually! pastebin get 4nRg9CHU /json")
- return
- end
- if not http or not http.websocketAsync then
- error("Please enable the http api or install CC:Tweaked")
- return
- end
- local url
- local token
- local ws
- local connected = false
- local id
- function resp(op, obj)
- local tb = {
- op = op,
- d = obj
- }
- return json.encode(tb)
- end
- local function noop() end
- local function recv()
- while connected do
- local event, _url, contents = os.pullEvent()
- if _url == url then
- if event == "websocket_failure" then
- os.queueEvent("wsnet_failure", contents)
- connected = false
- elseif event == "websocket_success" then
- os.queueEvent("wsnet_connectedint")
- ws = contents
- elseif event == "websocket_message" then
- local obj = json.decode(contents)
- if obj.op == 1 then
- ws.send(resp(2, {
- token = token
- }))
- elseif obj.op == 2 then
- os.queueEvent("wsnet_connected")
- id = obj.d.id
- elseif obj.op == 0 then
- print(obj.op)
- print(obj.e)
- print(obj.d.to)
- print(obj.d.from)
- print(obj.d.data)
- print("---")
- if obj.e == "NEW_MESSAGE" then
- if obj.d.to == id then
- os.queueEvent("wsnet_message", obj.d.from, obj.d.data)
- end
- end
- end
- end
- end
- end
- end
- function open(_url, _token, callback)
- url = _url
- token = _token
- ws = http.websocketAsync(url)
- connected = true
- parallel.waitForAll(recv, callback or noop)
- end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement