Skip to content

Instantly share code, notes, and snippets.

@jsimmons
Created July 21, 2010 03:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jsimmons/483979 to your computer and use it in GitHub Desktop.
Save jsimmons/483979 to your computer and use it in GitHub Desktop.
some irc stuff in lua for something
local pairs = pairs
local setmetatable = setmetatable
local unpack = unpack
module 'irc.client'
local meta = {}
meta.__index = meta
function meta:add_handler(command, callback)
if not self.handlers[command] then
self.handlers[command] = {callback}
else
table.insert(self.handlers[command], callback)
end
end
function meta:add_handlers(tab)
for cmd, cb in pairs(tab) do
self:add_handler(cmd, cb)
end
end
function meta:handle(prefix, cmd, args)
local cbs = self.handlers[cmd]
if cbs then
for _, cb in pairs(cbs) do
if cb(self, prefix, unpack(args)) then
break
end
end
end
end
function new(socket, send, handlers)
local client = {}
client = setmetatable(client, meta)
client.socket = socket
client.send = send
client.status = 'pre-auth'
client.handlers = {}
client:add_handlers(handlers)
return client
end
local socket = require 'socket'
local client = require 'irc.client'
local parser = require 'irc.parser'
local credentials = {
['username'] = 'password';
}
local server = assert(socket.bind('*', 6667))
server:settimeout(0)
local handlers = {
['PASS'] = function(self, prefix, pass)
if self.status ~= 'pre-auth' then return end
self.password = pass
return true
end;
['NICK'] = function(self, prefix, nick)
self.nick = nick
return true
end;
['USER'] = function(self, prefix, user, host, server, real)
local pass = credentials[user]
if self.password == credentials[user] and self.nick then
self.user = user
self.status = 'authed'
print('succesfully authed user ' .. self.user .. ' of nick ' .. self.nick)
else
error('Disconnect Me')
end
return true
end;
}
local clients = {}
local sockets = {server}
local read, write, err
while not err do
read, write, err = socket.select(sockets, nil)
for i = 1, #read do
local sock = read[i]
if sock == server then
local s = sock:accept()
local function send(self, data)
return s:send(data)
end
local c = client.new(send, handlers)
clients[c.socket] = c
table.insert(sockets, s)
else
local line = sock:receive('*l')
local prefix, cmd, args = parser.parse_line(line)
clients[sock]:handle(prefix, cmd, args)
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment