Advertisement
Doob

[OpenComputers] irc_modem

May 16th, 2017
565
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 2.29 KB | None | 0 0
  1. _G.imodem = {}
  2. imodem.channel = '#imodem'
  3. local server = 'irc.esper.net:6667'
  4. local internet = require('internet')
  5. local computer = require('computer')
  6. local event = require('event')
  7. local nick = 'x'..require('component').internet.address:sub(1, 8)
  8. local socket
  9.  
  10. local function login()
  11.   if socket then socket:close() end
  12.   socket = internet.open(server)
  13.   socket:setTimeout(0.05)
  14.   imodem.send_raw('USER '..nick..' 0 * :'..nick)
  15.   imodem.send_raw('NICK '..nick)
  16. end
  17.  
  18. imodem.send_raw = function(message)
  19.   socket:write(message..'\r\n')
  20.   socket:flush()
  21. end
  22.  
  23. imodem.broadcast = function(message)
  24.   if socket and imodem.channel then
  25.     imodem.send_raw('PRIVMSG '..imodem.channel..' :'..message)
  26.     return true
  27.   else
  28.     return false
  29.   end
  30. end
  31.  
  32. imodem.send = function(receiver, message)
  33.   if socket and receiver and message then
  34.     imodem.send_raw('PRIVMSG '..receiver..' :'..message)
  35.     return true
  36.   else
  37.     return false
  38.   end
  39. end
  40.  
  41. imodem.stop = function()
  42.   if imodem.timer then
  43.     if socket then
  44.       imodem.send_raw('QUIT')
  45.       socket:close()
  46.     end
  47.     event.cancel(imodem.timer)
  48.     imodem = nil
  49.   end
  50. end
  51.  
  52. imodem.timer = event.timer(0.5, function()
  53.   if not socket then login() end
  54.   repeat
  55.     local ok, line = pcall(socket.read, socket)
  56.     if ok then
  57.       if not line then login() end
  58.       local match, prefix = line:match('^(:(%S+) )')
  59.       if prefix then prefix = prefix:match('^[^!]+') end
  60.       if match then line = line:sub(#match+1) end
  61.       local match, command = line:match('^(([^:]%S*))')
  62.       if match then line = line:sub(#match+1) end
  63.       repeat
  64.         local match = line:match('^( ([^:]%S*))')
  65.         if match then
  66.           line = line:sub(#match+1)
  67.         end
  68.       until not match
  69.       local message = line:match('^ :(.*)$')
  70.       if command == '001' or command == '404' then
  71.         imodem.send_raw('JOIN '..imodem.channel)
  72.       elseif command == '433' or command == '436' then
  73.         nick = nick..string.char(math.random(97,122))
  74.         imodem.send_raw('NICK '..nick)
  75.       elseif command == 'PING' then
  76.         imodem.send_raw('PONG :'..message)
  77.       elseif command == 'PRIVMSG' then
  78.         computer.pushSignal('modem_message', nick, prefix, 0, 0, message)
  79.       end
  80.     end
  81.   until not ok
  82. end, math.huge)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement