Advertisement
ReIative

WSNET

Apr 23rd, 2018
81
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.14 KB | None | 0 0
  1. local function download_file(url, target)
  2. local ht = http.get(url)
  3. local data = ht.readAll()
  4. ht.close()
  5. local file = fs.open(target, "w")
  6. file.write(data)
  7. file.close()
  8. end
  9. local jsonloc = "/json"
  10. if (not fs.exists(jsonloc)) then
  11. local newjsonloc = shell and shell.resolveProgram("json") or nil
  12. if type(newjsonloc) ~= "string" then
  13. download_file("https://pastebin.com/raw/4nRg9CHU", "/json")
  14. else
  15. jsonloc = newjsonloc
  16. end
  17. end
  18. os.loadAPI("/json")
  19. if not json then
  20. error("Failed to load JSON api, download it manually! pastebin get 4nRg9CHU /json")
  21. return
  22. end
  23. if not http or not http.websocketAsync then
  24. error("Please enable the http api or install CC:Tweaked")
  25. return
  26. end
  27.  
  28. local url
  29. local token
  30. local ws
  31. local connected = false
  32. local id
  33. function resp(op, obj)
  34. local tb = {
  35. op = op,
  36. d = obj
  37. }
  38. return json.encode(tb)
  39. end
  40. local function noop() end
  41. local function recv()
  42. while connected do
  43. local event, _url, contents = os.pullEvent()
  44. if _url == url then
  45. if event == "websocket_failure" then
  46. os.queueEvent("wsnet_failure", contents)
  47. connected = false
  48. elseif event == "websocket_success" then
  49. os.queueEvent("wsnet_connectedint")
  50. ws = contents
  51. elseif event == "websocket_message" then
  52. local obj = json.decode(contents)
  53. if obj.op == 1 then
  54. ws.send(resp(2, {
  55. token = token
  56. }))
  57. elseif obj.op == 2 then
  58. os.queueEvent("wsnet_connected")
  59. id = obj.d.id
  60. elseif obj.op == 0 then
  61. print(obj.op)
  62. print(obj.e)
  63. print(obj.d.to)
  64. print(obj.d.from)
  65. print(obj.d.data)
  66. print("---")
  67. if obj.e == "NEW_MESSAGE" then
  68. if obj.d.to == id then
  69. os.queueEvent("wsnet_message", obj.d.from, obj.d.data)
  70. end
  71. end
  72. end
  73. end
  74. end
  75. end
  76. end
  77. function open(_url, _token, callback)
  78. url = _url
  79. token = _token
  80. ws = http.websocketAsync(url)
  81. connected = true
  82. parallel.waitForAll(recv, callback or noop)
  83. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement