98 lines
1.7 KiB
Lua
98 lines
1.7 KiB
Lua
local irc = {}
|
|
local tslp = os.epoch "utc"
|
|
local timeout_timer = os.startTimer(6)
|
|
local ws
|
|
function init_ws()
|
|
ws = nil
|
|
while not ws do
|
|
sleep(0.3)
|
|
ws = http.websocket("wss://heav.osmarks.tk/ws/irc")
|
|
end
|
|
end
|
|
|
|
function irc.sendRaw(d)
|
|
ws.send(textutils.serializeJSON(d))
|
|
end
|
|
|
|
function irc.listen(timeout)
|
|
local b
|
|
if timeout then b = os.startTimer(timeout) end
|
|
while true do
|
|
local e,x,y = os.pullEvent()
|
|
if e=="timer" and x==b then
|
|
return false
|
|
elseif e=="timer" and x==timeout_timer then
|
|
error("Timed out")
|
|
elseif e=="websocket_message" and x == "wss://heav.osmarks.tk/ws/irc" then
|
|
local d = textutils.unserializeJSON(y)
|
|
if d.type=="ping" then
|
|
irc.sendRaw({
|
|
type="pong",
|
|
n = d.n,
|
|
})
|
|
tslp = os.epoch "utc"
|
|
os.cancelTimer(timeout_timer)
|
|
timeout_timer = os.startTimer(6)
|
|
else
|
|
if b then os.cancelTimer(b) end
|
|
return true, d
|
|
end
|
|
end
|
|
end
|
|
end
|
|
|
|
function irc.connect(ip, port, nick)
|
|
init_ws()
|
|
irc.sendRaw({
|
|
type="server",
|
|
ip=ip,
|
|
port=port,
|
|
})
|
|
local s,bees = irc.listen(5)
|
|
if not s then
|
|
error("Couldn't connect to the HNode, apparently")
|
|
else
|
|
if bees.type=="error" then
|
|
error(bees.reason)
|
|
end
|
|
end
|
|
irc.sendRaw({
|
|
type="nick",
|
|
nick=nick,
|
|
})
|
|
s,bees = irc.listen(5)
|
|
if not s then
|
|
error("Couldn't connect to the HNode, apparently")
|
|
else
|
|
if bees.type=="error" then
|
|
error(bees.reason)
|
|
end
|
|
end
|
|
end
|
|
|
|
function irc.join(channel)
|
|
irc.sendRaw({
|
|
type="join",
|
|
channel=channel,
|
|
})
|
|
local s,bees = irc.listen(5)
|
|
if not s then
|
|
error("Couldn't connect to the HNode, apparently")
|
|
else
|
|
if bees.type=="error" then
|
|
error(bees.reason)
|
|
end
|
|
end
|
|
end
|
|
|
|
function irc.msg(channel,content)
|
|
irc.sendRaw({
|
|
type="message",
|
|
channel=channel,
|
|
content=content
|
|
})
|
|
end
|
|
|
|
return irc
|
|
|